Compare commits

...
Author SHA1 Message Date
HyeongBaeYang 92cfeabe19 Merge remote-tracking branch 'origin/main' into feat/watch-summary 2026-10-13 15:36:50 +09:00
HyeongBaeYangandClaude Opus 5.5 e270261e32 feat: 워치 페이스 푸시로 앱 설치 때 날씨각 스킨 같이 적용(Wear OS 6+), 앱 첫 장을 오늘 남은 시간→주변 축제 순으로
Play 스토어 심사에 낸 1(0.1) 빌드와 같은 코드

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:36:50 +09:00
minaChoi 2b1b929f8f feat: 히어로 말풍선을 '오늘은' 대신 칸 이름으로 (지금은·아침은·낮은·저녁은·밤은 ~각!) 2026-10-13 14:13:56 +09:00
minaChoi 3712c7561a feat: 아이콘이 겹치던 각 9개에 전용 아이콘 (한강밤바람·트로트·파전·빙수·이불빨래·실내건조·꽃구경·붕어빵·싱잉인더레인) 2026-10-13 13:36:54 +09:00
minaChoi 0b536e1f90 fix: 지금 구간 각 점수와 '지금' 칸은 지금 시각부터 (이미 지난 시각의 단기예보 비가 남아 우산각 1위·비 아이콘이 나오던 것) 2026-10-13 13:33:10 +09:00
minaChoi 260ded8c79 Merge remote-tracking branch 'origin/main' into feat/meeting-1008 2026-10-13 13:22:42 +09:00
minaChoi 012d8a4821 fix: 초단기예보가 닿는 시간은 비·비 없음 모두 초단기예보를 따르게 (단기예보에 남은 비로 '지금' 칸·우산각이 비로 나오던 것) 2026-10-13 13:22:42 +09:00
HyeongBaeYang ee46a101db Merge remote-tracking branch 'origin/main' into feat/watch-summary 2026-10-13 13:01:59 +09:00
HyeongBaeYangandClaude Opus 5.5 a21283651e feat: 개인정보처리방침 페이지(/privacy) 추가 — Play 스토어 등록용
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 13:01:59 +09:00
minaChoi e28a2e297e Merge remote-tracking branch 'origin/main' into feat/meeting-1008 2026-10-13 11:42:36 +09:00
minaChoi 043210c049 chore: 메인 제목을 원래대로 '날씨각 · 오늘 날씨 지수, 노을, 주말 행사' 2026-10-13 11:42:29 +09:00
minaChoi 29700f9d76 fix: 각 탭 1~3위 양옆 카드 높이를 같게(이름이 두 줄이면 2위만 커지던 것), 배포 때 피드 캐시 비움(오늘 탭 순위가 옛 규칙으로 남던 것) 2026-10-13 11:21:04 +09:00
HyeongBaeYang d95c69e3b7 Merge remote-tracking branch 'origin/main' into feat/watch-summary 2026-10-13 11:17:14 +09:00
HyeongBaeYangandClaude Opus 5.5 fd4a00bcf7 feat: 워치 앱·스킨에 새 각 아이콘 11종(+스킨 비·눈·노을) 추가, 축제 문구를 '주변 축제'로 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:17:14 +09:00
minaChoi 18a7cffb39 Merge remote-tracking branch 'origin/main' into feat/meeting-1008 2026-10-13 11:09:15 +09:00
minaChoi 8a7b269c04 chore: 메인 제목을 '날씨각'만으로 — 검색 노출 비교 테스트 2026-10-13 11:09:00 +09:00
61 changed files with 420 additions and 212 deletions

No files matched your search

+9 -9
View File
@@ -2568,7 +2568,7 @@
{ {
"code": "flower", "code": "flower",
"name": "꽃구경각", "name": "꽃구경각",
"icon": "garden", "icon": "flower",
"category": 1, "category": 1,
"is_fun": false, "is_fun": false,
"is_core": false, "is_core": false,
@@ -2652,7 +2652,7 @@
{ {
"code": "blanket", "code": "blanket",
"name": "이불빨래각", "name": "이불빨래각",
"icon": "laundry", "icon": "blanket",
"category": 3, "category": 3,
"is_fun": false, "is_fun": false,
"is_core": false, "is_core": false,
@@ -2731,7 +2731,7 @@
{ {
"code": "bingsu", "code": "bingsu",
"name": "빙수각", "name": "빙수각",
"icon": "iced_hot", "icon": "bingsu",
"category": 2, "category": 2,
"is_fun": true, "is_fun": true,
"is_core": false, "is_core": false,
@@ -2793,7 +2793,7 @@
{ {
"code": "indoordry", "code": "indoordry",
"name": "실내건조각", "name": "실내건조각",
"icon": "laundry", "icon": "indoordry",
"category": 3, "category": 3,
"is_fun": false, "is_fun": false,
"is_core": false, "is_core": false,
@@ -2860,7 +2860,7 @@
{ {
"code": "riverwind", "code": "riverwind",
"name": "한강밤바람각", "name": "한강밤바람각",
"icon": "yajang", "icon": "riverwind",
"category": 1, "category": 1,
"is_fun": false, "is_fun": false,
"is_core": false, "is_core": false,
@@ -3318,7 +3318,7 @@
{ {
"code": "bungeoppang", "code": "bungeoppang",
"name": "붕어빵각", "name": "붕어빵각",
"icon": "sweet_potato", "icon": "bungeoppang",
"category": 2, "category": 2,
"is_fun": true, "is_fun": true,
"is_core": false, "is_core": false,
@@ -3494,7 +3494,7 @@
{ {
"code": "pajeon", "code": "pajeon",
"name": "파전각", "name": "파전각",
"icon": "makgeolli", "icon": "pajeon",
"category": 2, "category": 2,
"is_fun": true, "is_fun": true,
"is_core": false, "is_core": false,
@@ -3606,7 +3606,7 @@
{ {
"code": "trot", "code": "trot",
"name": "트로트각", "name": "트로트각",
"icon": "picnic", "icon": "trot",
"category": 1, "category": 1,
"is_fun": true, "is_fun": true,
"is_core": false, "is_core": false,
@@ -3676,7 +3676,7 @@
{ {
"code": "singing_rain", "code": "singing_rain",
"name": "싱잉인더레인각", "name": "싱잉인더레인각",
"icon": "umbrella", "icon": "singing_rain",
"category": 1, "category": 1,
"is_fun": true, "is_fun": true,
"is_core": false, "is_core": false,
+4 -3
View File
@@ -153,12 +153,13 @@ def feed_day(now: datetime) -> date:
def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int: def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int:
"""다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신 중 가장 빠른 쪽.""" """다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신·정각(지금 구간이 줄어듦) 중 가장 빠른 쪽."""
day = now.date() day = now.date()
at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731 at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731
sunset = sunset_at.astimezone(KST) sunset = sunset_at.astimezone(KST)
changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET, changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET,
at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY] at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY,
now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)]
air = now.replace(minute=20, second=0, microsecond=0) air = now.replace(minute=20, second=0, microsecond=0)
changes.append(air if air > now else air + timedelta(hours=1)) changes.append(air if air > now else air + timedelta(hours=1))
nxt = min(c for c in changes if c > now) nxt = min(c for c in changes if c > now)
@@ -427,7 +428,7 @@ class FeedService:
top = board.ranked[0] if board and board.ranked else None top = board.ranked[0] if board and board.ranked else None
bubble = None bubble = None
if top is not None: if top is not None:
bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요" bubble = f"지금은 {top.definition.name}!" if top.score.score >= 70 else "지금은 쉬어 가요"
x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None) x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None)
return Hero( return Hero(
now_at=now, sky_mode=_SKY_MODE[slot], now_at=now, sky_mode=_SKY_MODE[slot],
+21 -19
View File
@@ -21,9 +21,8 @@ from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, e
from services.calc.moon import night, up_ratio, view_line from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot from services.external.open_meteo import is_dark_slot
from services.now_service import RainHour, ultra_hours
from services.warning_service import WarningService from services.warning_service import WarningService
from services.weather_service import WeatherService from services.weather_service import WeatherService, ultra_hours, with_ultra_rain
# 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다. # 시간별 예보로 늘 계산하는 날 수 (오늘~모레). 이번 주말은 시간별 예보가 없으면 중기예보로 예상 점수를 낸다.
DAYS = 3 DAYS = 3
@@ -176,18 +175,6 @@ def windows_for(
return out return out
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
"""초단기예보가 비라고 한 시각은 그 비로 바꾼 사본. 단기예보는 3시간마다라 지금 내리는 비를 놓친다."""
out = dict(by_at)
for h in ultra or []:
r = out.get(h.at)
if r is None or h.rain_type is RainType.NONE or r.rain_type != RainType.NONE.value:
continue
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": max(float(r.rain_mm), h.rain_mm)})
return out
EARLY = "early" # 0~5시: 전날 밤 구간 EARLY = "early" # 0~5시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간) MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
@@ -208,19 +195,32 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
def slot_results( def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
now: Optional[datetime] = None,
) -> dict[str, Result]: ) -> dict[str, Result]:
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다.""" """그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다."""
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()} hours_by_slot = slot_hours(day, sunset_at)
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()}
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR))) parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR)))
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0)) need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0))
out = {} out = {}
for key, windows in parts.items(): for key, windows in parts.items():
result = evaluate(defn, [w for w in windows if len(w) >= need], ctx) k_need = min(need, len(hours_by_slot[key])) if key == cur else need
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx)
if result is not None: if result is not None:
out[key] = result out[key] = result
return out return out
def _trim_passed(hours_by_slot: dict[str, set[int]], day: date, sunset_at: datetime, now: datetime) -> Optional[str]:
"""지금 구간에서 이미 지난 시각을 뺀다(지난 단기예보 비가 지금 점수에 남지 않게). 지금 구간 이름, 오늘이 아니면 None."""
hour = int((now - kst_midnight(day)).total_seconds() // 3600)
cur = next((k for k, hours in hours_by_slot.items() if hour in hours), None)
if cur is not None:
hours_by_slot[cur] = {h for h in hours_by_slot[cur] if h >= hour}
return cur
def _slot_json(r: Result) -> dict: def _slot_json(r: Result) -> dict:
return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes} return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes}
@@ -390,7 +390,7 @@ class IndexService:
) )
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()} weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) 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 inputs_at = max(issued, air.measured_at) if air else issued
@@ -398,6 +398,8 @@ class IndexService:
inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values())) inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values()))
if ultra is not None: if ultra is not None:
inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY) inputs_at = max(inputs_at, latest_ultra_base(now) + ULTRA_DELAY)
# 지금 구간은 지금 시각부터 보므로 정각마다 다시 계산
inputs_at = max(inputs_at, now.replace(minute=0, second=0, microsecond=0))
err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today)) err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today))
_, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1])) _, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1]))
_, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today)) _, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today))
@@ -423,7 +425,7 @@ class IndexService:
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om) result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
if result is None: if result is None:
continue continue
parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {} parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at, now) if day == today else {}
out.append({ out.append({
"region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary, "region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary,
**{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes, **{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes,
+2 -60
View File
@@ -3,39 +3,23 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Optional from typing import Optional
import httpx
import orjson
from fastapi import Depends from fastapi import Depends
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.db_session_manager import DB_SESSION_MNG
from common.database.model.models import AirQuality, Region, WeatherHourly from common.database.model.models import AirQuality, Region, WeatherHourly
from common.enums import AirGrade, ErrorType, RainType, Sky from common.enums import AirGrade, ErrorType, RainType, Sky
from common.logger import LOG from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, now_kst from common.utils.kma_time import KST, kst_midnight, now_kst
from common.utils.text import hour_label from common.utils.text import hour_label
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD from crud.weather_crud import WeatherCRUD
from services.air_service import GRADE_LABEL, AirService from services.air_service import GRADE_LABEL, AirService
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kma import fetch_ultra, parse_ultra
from services.warning_service import WarningItem, WarningService from services.warning_service import WarningItem, WarningService
from services.weather_service import WeatherService from services.weather_service import RainHour, WeatherService, ultra_hours
_FETCH_ERRORS = (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError)
_COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19)) _COMMUTE = (("내일 출근 8시", 8), ("내일 퇴근 7시", 19))
@dataclass
class RainHour:
at: datetime
rain_type: RainType
rain_mm: float
lightning: bool = False
@dataclass @dataclass
class CommuteRow: class CommuteRow:
label: str label: str
@@ -146,45 +130,3 @@ class NowService:
async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]: async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]:
return await ultra_hours(region, now) return await ultra_hours(region, now)
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
cached = await REDIS.conn.get(key)
if not cached:
return None
data = orjson.loads(cached)
if data["base"] != base.isoformat():
return None
return [
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
for h in data["hours"]
]
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
key = f"ultra:{region.code}"
base = latest_ultra_base(now)
try:
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
if attempt:
await asyncio.sleep(_ULTRA_WAIT_SEC)
if (hours := await _cached_ultra(key, base)) is not None:
return hours
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
if not acquired:
continue
async with httpx.AsyncClient(timeout=10) as client:
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
return hours
return None
except _FETCH_ERRORS as e:
LOG.error(f"[now] ultra {region.code}: {e}")
return None
+70 -5
View File
@@ -5,6 +5,7 @@ from datetime import date, datetime, timedelta
from typing import Optional from typing import Optional
import httpx import httpx
import orjson
from fastapi import Depends from fastapi import Depends
from redis.exceptions import RedisError from redis.exceptions import RedisError
@@ -14,14 +15,14 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import Region, SunTime, WeatherHourly from common.database.model.models import Region, SunTime, WeatherHourly
from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone from common.enums import ErrorType, RainType, Sky, SkyType, SlotTone
from common.logger import LOG from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, latest_vilage_base, now_kst from common.utils.kma_time import KST, kst_midnight, latest_ultra_base, latest_vilage_base, now_kst
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD from crud.sky_crud import SkyCRUD
from crud.weather_crud import WeatherCRUD from crud.weather_crud import WeatherCRUD
from services.calc.sun import sun_times from services.calc.sun import sun_times
from services.calc.weather_calc import discomfort_index, feels_like_c from services.calc.weather_calc import discomfort_index, feels_like_c
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kma import day_start_base, fetch_mid, fetch_vilage, latest_mid_base, parse_mid, parse_vilage from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
SLOT_HOURS = range(0, 24, 3) SLOT_HOURS = range(0, 24, 3)
_WAIT_STEPS, _WAIT_SEC = 15, 0.2 _WAIT_STEPS, _WAIT_SEC = 15, 0.2
@@ -31,6 +32,14 @@ MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
_background: set[asyncio.Task] = set() _background: set[asyncio.Task] = set()
@dataclass
class RainHour:
at: datetime
rain_type: RainType
rain_mm: float
lightning: bool = False
@dataclass @dataclass
class Slot: class Slot:
at: datetime at: datetime
@@ -49,6 +58,18 @@ class TodayWeather:
slots: list[Slot] slots: list[Slot]
def with_ultra_rain(by_at: dict[datetime, WeatherHourly], ultra: Optional[list[RainHour]]) -> dict[datetime, WeatherHourly]:
"""초단기예보가 닿는 시각은 비·비 없음 모두 초단기예보로 바꾼 사본. 단기예보는 3시간마다라 그 사이 바뀐 비를 놓친다."""
out = dict(by_at)
for h in ultra or []:
r = out.get(h.at)
if r is None or (h.rain_type.value, h.rain_mm) == (r.rain_type, float(r.rain_mm)):
continue
cols = {c.key: getattr(r, c.key) for c in WeatherHourly.__table__.columns}
out[h.at] = WeatherHourly(**{**cols, "rain_type": h.rain_type.value, "rain_mm": h.rain_mm})
return out
def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]: def _hourly_rows(region_code: str, hourly: dict[datetime, dict], issued: datetime) -> list[dict]:
rows = [] rows = []
for at, v in hourly.items(): for at, v in hourly.items():
@@ -138,7 +159,7 @@ class WeatherService:
return ErrorType.NOT_FOUND, None return ErrorType.NOT_FOUND, None
now = now_kst() now = now_kst()
await self.ensure_vilage(region, now) _, ultra = await asyncio.gather(self.ensure_vilage(region, now), ultra_hours(region, now, wait=True))
day = day or now.date() day = day or now.date()
sun = await self._ensure_sun(region, day) sun = await self._ensure_sun(region, day)
start = kst_midnight(day) start = kst_midnight(day)
@@ -154,11 +175,13 @@ class WeatherService:
sunset_score = next( sunset_score = next(
(x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None (x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value and x.score_date == day), None
) )
by_at = {r.forecast_at: r for r in rows} by_at = with_ultra_rain({r.forecast_at: r for r in rows}, ultra)
slots = [] slots = []
hour_now = now.replace(minute=0, second=0, microsecond=0)
for h in SLOT_HOURS: for h in SLOT_HOURS:
at = start + timedelta(hours=h) at = start + timedelta(hours=h)
row = by_at.get(at) # 지금이 든 칸은 칸 첫 시각 대신 지금 시각 예보 (이미 지난 시각의 비가 '지금'으로 보이지 않게)
row = by_at.get(hour_now) if at <= now < at + timedelta(hours=3) and hour_now in by_at else by_at.get(at)
icon, tone, note = _slot_view(at, row, sun) icon, tone, note = _slot_view(at, row, sun)
if note == "노을" and sunset_score is not None: if note == "노을" and sunset_score is not None:
note = f"노을 {sunset_score}" note = f"노을 {sunset_score}"
@@ -262,3 +285,45 @@ class WeatherService:
} }
await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)]) await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_sun(s, row)])
return SunTime(**row) return SunTime(**row)
_ULTRA_WAIT_SEC, _ULTRA_WAIT_TRIES = 0.3, 30 # 다른 요청이 받아 오는 중이면 캐시가 찰 때까지 약 9초 기다린다
async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]:
cached = await REDIS.conn.get(key)
if not cached:
return None
data = orjson.loads(cached)
if data["base"] != base.isoformat():
return None
return [
RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False))
for h in data["hours"]
]
async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]:
"""초단기예보(앞으로 6시간 비). 실패하면 None. 다른 요청이 받아 오는 중이면 wait 일 때만 기다리고 아니면 None."""
key = f"ultra:{region.code}"
base = latest_ultra_base(now)
try:
for attempt in range(_ULTRA_WAIT_TRIES if wait else 1):
if attempt:
await asyncio.sleep(_ULTRA_WAIT_SEC)
if (hours := await _cached_ultra(key, base)) is not None:
return hours
async with redis_lock(f"lock:ultra:{region.code}") as acquired:
if not acquired:
continue
async with httpx.AsyncClient(timeout=10) as client:
parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base))
hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed]
ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds())
payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]}
await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60))
return hours
return None
except (DataGoKrNotConfigured, DataGoKrRequestFailed, RedisError) as e:
LOG.error(f"[now] ultra {region.code}: {e}")
return None
+1 -2
View File
@@ -80,7 +80,6 @@ def offline(monkeypatch):
import scheduler.jobs as jobs import scheduler.jobs as jobs
import services.air_service as air_service import services.air_service as air_service
import services.now_service as now_service
import services.season_service as season_service import services.season_service as season_service
import services.sky_service as sky_service import services.sky_service as sky_service
import services.warning_service as warning_service import services.warning_service as warning_service
@@ -118,7 +117,7 @@ def offline(monkeypatch):
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")] clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear))) monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")]))) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}])) monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{ monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
"stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1", "stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
+26 -7
View File
@@ -6,8 +6,8 @@ from common.enums import RainType, Sky
from common.utils.kma_time import KST, kst_midnight from common.utils.kma_time import KST, kst_midnight
from services.calc.day_slot import slot_hours from services.calc.day_slot import slot_hours
from services.calc.index_calc import Context from services.calc.index_calc import Context
from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results, with_ultra_rain from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results
from services.now_service import RainHour from services.weather_service import RainHour, with_ultra_rain
DAY = date(2026, 10, 8) DAY = date(2026, 10, 8)
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST) SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
@@ -81,15 +81,17 @@ def _hourly(h: int, rain: RainType = RainType.NONE) -> WeatherHourly:
) )
def test_ultra_rain_marks_dry_forecast_hours_as_rain(): def test_ultra_overrides_vilage_rain_both_ways():
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER))} """초단기예보가 닿는 시각은 초단기예보가 이긴다: 단기예보가 맑아도 비로, 단기예보가 비여도 비 없음으로."""
by_at = {r.forecast_at: r for r in (_hourly(9), _hourly(10), _hourly(11, RainType.SHOWER), _hourly(12, RainType.RAIN))}
at = lambda h: kst_midnight(DAY) + timedelta(hours=h) # noqa: E731 at = lambda h: kst_midnight(DAY) + timedelta(hours=h) # noqa: E731
ultra = [RainHour(at=at(10), rain_type=RainType.RAIN, rain_mm=1.5), RainHour(at=at(9), rain_type=RainType.NONE, rain_mm=0), ultra = [RainHour(at=at(10), rain_type=RainType.RAIN, rain_mm=1.5), RainHour(at=at(9), rain_type=RainType.NONE, rain_mm=0),
RainHour(at=at(11), rain_type=RainType.RAIN, rain_mm=3.0)] RainHour(at=at(11), rain_type=RainType.NONE, rain_mm=0)]
out = with_ultra_rain(by_at, ultra) out = with_ultra_rain(by_at, ultra)
assert (out[at(10)].rain_type, float(out[at(10)].rain_mm)) == (RainType.RAIN.value, 1.5) assert (out[at(10)].rain_type, float(out[at(10)].rain_mm)) == (RainType.RAIN.value, 1.5)
assert out[at(9)] is by_at[at(9)] and out[at(11)] is by_at[at(11)] assert (out[at(11)].rain_type, float(out[at(11)].rain_mm)) == (RainType.NONE.value, 0)
assert by_at[at(10)].rain_type == RainType.NONE.value assert out[at(9)] is by_at[at(9)] and out[at(12)] is by_at[at(12)]
assert by_at[at(10)].rain_type == RainType.NONE.value and by_at[at(11)].rain_type == RainType.SHOWER.value
def test_ultra_rain_lowers_slot_score(): def test_ultra_rain_lowers_slot_score():
@@ -106,3 +108,20 @@ def test_slot_needs_two_overlapping_hours():
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET) assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
def test_current_slot_skips_passed_hours():
"""13:30이면 낮 구간(11~15시)은 13시부터 본다. 11~12시에만 온 비는 지금 점수를 깎지 않는다. 지난 아침 구간은 그대로."""
defn = _defn([{"from": 5, "to": 24}])
by_at = {r.forecast_at: r for r in (_hourly(h, RainType.RAIN if h in (11, 12) else RainType.NONE) for h in range(5, 30))}
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
with_now = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET, now)
without = slot_results(defn, DAY, REGION, by_at, {}, CTX, SUNSET)
assert with_now["day"].score > without["day"].score
assert with_now["morning"].score == without["morning"].score
def test_current_slot_keeps_last_hour():
"""구간 끝 한 시간만 남아도 지금 구간 점수를 낸다."""
now = datetime(2026, 10, 8, 15, 10, tzinfo=KST)
assert "day" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
+1 -2
View File
@@ -4,7 +4,6 @@ from types import SimpleNamespace
import pytest import pytest
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
import services.now_service as now_service
import services.air_service as air_service import services.air_service as air_service
import services.warning_service as warning_service import services.warning_service as warning_service
import services.weather_service as weather_service import services.weather_service as weather_service
@@ -52,7 +51,7 @@ def fakes(monkeypatch):
}])) }]))
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([])) monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid())) monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async([])) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async([]))
@pytest.mark.anyio @pytest.mark.anyio
+1 -2
View File
@@ -2,7 +2,6 @@ import pytest
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
import services.air_service as air_service import services.air_service as air_service
import services.now_service as now_service
import services.season_service as season_service import services.season_service as season_service
import services.sky_service as sky_service import services.sky_service as sky_service
import services.warning_service as warning_service import services.warning_service as warning_service
@@ -16,7 +15,7 @@ REGION = "1114000000"
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"] ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
SOURCES = { SOURCES = {
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed), "vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed), "ultra": (weather_service, "fetch_ultra", DataGoKrRequestFailed),
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed), "air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed), "warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed), "clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
+2 -2
View File
@@ -4,7 +4,7 @@ from types import SimpleNamespace
import pytest import pytest
from httpx import ASGITransport, AsyncClient from httpx import ASGITransport, AsyncClient
import services.now_service as now_service import services.weather_service as weather_service
import services.week_service as week_service import services.week_service as week_service
from common.cache.redis_client import REDIS from common.cache.redis_client import REDIS
from common.utils.kma_time import KST, now_kst from common.utils.kma_time import KST, now_kst
@@ -94,7 +94,7 @@ async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v} {"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")] for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
] ]
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(items)) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(items))
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다 # 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}") await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
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:
+2 -3
View File
@@ -5,7 +5,6 @@ from httpx import ASGITransport, AsyncClient
from sqlalchemy import text from sqlalchemy import text
import services.air_service as air_service import services.air_service as air_service
import services.now_service as now_service
import services.warning_service as warning_service import services.warning_service as warning_service
import services.weather_service as weather_service import services.weather_service as weather_service
from common.cache.redis_client import REDIS from common.cache.redis_client import REDIS
@@ -63,7 +62,7 @@ async def clean():
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean): async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
now = now_kst() now = now_kst()
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage())) monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra())) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}])) monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{ monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1", "stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
@@ -92,7 +91,7 @@ async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
raise DataGoKrRequestFailed("HTTP 504") raise DataGoKrRequestFailed("HTTP 504")
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage())) monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra())) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(_ultra()))
monkeypatch.setattr(air_service, "fetch_stations", fail) monkeypatch.setattr(air_service, "fetch_stations", fail)
monkeypatch.setattr(air_service, "fetch_realtime", fail) monkeypatch.setattr(air_service, "fetch_realtime", fail)
monkeypatch.setattr(warning_service, "fetch_warning_events", fail) monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
+2
View File
@@ -19,6 +19,8 @@ docker compose up -d --wait postgres redis
docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql docker compose exec -T postgres psql -q -v ON_ERROR_STOP=1 -U "$DB_USER" -d "$DB_NAME" < backend/postgres-init/init.sql
docker compose up -d --build backend worker frontend docker compose up -d --build backend worker frontend
docker compose exec -T backend python scripts/load_seed.py docker compose exec -T backend python scripts/load_seed.py
# 피드 캐시는 최대 1시간이라, 각 규칙이 바뀌어도 오늘 탭만 옛 순위로 남는다
docker compose exec -T redis sh -c "redis-cli --scan --pattern 'feed:*' | xargs -r redis-cli del" >/dev/null
if [ "${1:-}" = "--restore-db" ]; then if [ "${1:-}" = "--restore-db" ]; then
dump="${2:?덤프 파일 경로가 필요합니다}" dump="${2:?덤프 파일 경로가 필요합니다}"
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

+60
View File
@@ -0,0 +1,60 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>개인정보처리방침 - 날씨각</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<style>
body { margin: 0; padding: 32px 20px 64px; font: 15px/1.7 -apple-system, BlinkMacSystemFont, "Apple SD Gothic Neo", "Malgun Gothic", sans-serif; color: #28304a; background: #f1f8ff; }
main { max-width: 720px; margin: 0 auto; }
h1 { font-size: 26px; margin: 0 0 4px; }
h2 { font-size: 18px; margin: 32px 0 8px; }
table { width: 100%; border-collapse: collapse; background: #fff; font-size: 14px; }
th, td { border: 1px solid #d9e5f4; padding: 8px 10px; text-align: left; vertical-align: top; }
th { background: #e6f1ff; }
.muted { color: #5a6380; }
</style>
</head>
<body>
<main>
<h1>개인정보처리방침</h1>
<p class="muted">시행일: 2026년 10월 13일</p>
<p>AIO2O(이하 "회사")는 날씨각 웹 서비스(이하 "웹")와 날씨각 Wear OS 앱(이하 "워치 앱")을 운영하며, 「개인정보 보호법」에 따라 이용자의 개인정보를 다음과 같이 처리합니다.</p>
<h2>1. 수집하는 개인정보와 목적</h2>
<table>
<tr><th>구분</th><th>항목</th><th>목적</th></tr>
<tr><td>웹 회원가입·로그인</td><td>아이디, 비밀번호(암호화 저장), 닉네임 / Google 로그인 시 Google 계정 고유 식별자</td><td>회원 식별, 좋아요·저장·댓글 기능 제공</td></tr>
<tr><td>웹·워치 앱 위치</td><td>대략적인 위치(위도·경도)</td><td>가장 가까운 지역(구)의 날씨와 주변 축제를 보여주기 위해 사용합니다. 위치 좌표는 지역을 찾는 데만 쓰고 서버에 저장하지 않습니다.</td></tr>
<tr><td>서비스 이용</td><td>접속 기록(IP 주소, 접속 시각, 브라우저 정보), 선택한 지역</td><td>서비스 운영, 오류 확인, 이용 통계</td></tr>
</table>
<p>위치 권한은 선택 사항입니다. 허용하지 않아도 지역을 직접 골라 이용할 수 있습니다. 워치 앱은 회원가입이나 로그인 없이 이용할 수 있습니다.</p>
<h2>2. 보유 및 이용 기간</h2>
<p>회원 정보는 회원 탈퇴 시까지 보관하며, 탈퇴 요청을 받으면 지체 없이 파기합니다. 접속 기록은 「통신비밀보호법」에 따라 3개월간 보관합니다.</p>
<h2>3. 제3자 제공 및 처리 위탁</h2>
<p>회사는 이용자의 개인정보를 제3자에게 제공하지 않습니다. 이용 통계 분석을 위해 Google Analytics(Google LLC)를 사용하며, 이 과정에서 쿠키와 기기 정보가 Google에 전송될 수 있습니다. 브라우저 설정에서 쿠키를 거부할 수 있습니다.</p>
<h2>4. 파기 절차 및 방법</h2>
<p>보유 기간이 끝나거나 목적이 달성된 개인정보는 지체 없이 복구할 수 없는 방법으로 삭제합니다.</p>
<h2>5. 이용자의 권리</h2>
<p>이용자는 언제든지 자신의 개인정보 열람, 정정, 삭제, 처리 정지와 회원 탈퇴를 요청할 수 있습니다. 아래 연락처로 요청하시면 지체 없이 처리합니다. 워치 앱의 위치 권한은 기기 설정에서 언제든지 끌 수 있습니다.</p>
<h2>6. 안전성 확보 조치</h2>
<p>비밀번호는 암호화하여 저장하고, 개인정보에 접근할 수 있는 인원을 최소한으로 제한합니다.</p>
<h2>7. 아동의 개인정보</h2>
<p>회사는 만 14세 미만 아동의 개인정보를 알면서 수집하지 않습니다.</p>
<h2>8. 개인정보 보호책임자</h2>
<p>운영자: AIO2O<br />이메일: <a href="mailto:o2odev@o2o.kr">o2odev@o2o.kr</a></p>
<h2>9. 변경 안내</h2>
<p>이 방침이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.</p>
</main>
</body>
</html>
+6 -6
View File
@@ -27,11 +27,11 @@ const GRID_SKELS = Array.from({ length: 9 }, (_, i) => i)
/** 1~3위 받침대와 같은 칸(가운데가 높은 3칸)의 스켈레톤 */ /** 1~3위 받침대와 같은 칸(가운데가 높은 3칸)의 스켈레톤 */
function PodiumSkel() { function PodiumSkel() {
return ( return (
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3" aria-hidden="true"> <div className="grid grid-cols-[1fr_1.15fr_1fr] gap-1.5 px-3 pt-3" aria-hidden="true">
{[1, 0, 2].map((k) => ( {[1, 0, 2].map((k) => (
<span key={k} className={cx('flex flex-col items-center rounded-3xl bg-white px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'py-4' : 'py-3')}> <span key={k} className={cx('flex flex-col items-center rounded-3xl bg-white px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'py-4' : 'mt-6 py-3')}>
<Skel shape className={cx('aspect-square rounded-full', k === 0 ? 'w-20' : 'w-[62px]')} /> <Skel shape className={cx('aspect-square rounded-full', k === 0 ? 'w-20' : 'w-[62px]')} />
<b className="mt-1.5 font-jua text-base font-normal"> <b className="mt-1.5 flex flex-1 items-center font-jua text-base font-normal">
<Skel className="w-16" /> <Skel className="w-16" />
</b> </b>
<em className="font-bagel text-[30px] leading-[1.05] not-italic"> <em className="font-bagel text-[30px] leading-[1.05] not-italic">
@@ -91,7 +91,7 @@ export function GakPage() {
<StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} className="inset-x-3 top-3 bottom-0" /> <StateBox load={load} onRetry={() => q.refetch()} empty="오늘 1~3위를 아직 못 정했어요." hold={<PodiumSkel />} className="inset-x-3 top-3 bottom-0" />
) )
) : ( ) : (
<div className={cx('grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}> <div className={cx('grid grid-cols-[1fr_1.15fr_1fr] gap-1.5 px-3 pt-3 transition-opacity', q.isPlaceholderData && 'opacity-60')}>
{[1, 0, 2].map((k) => { {[1, 0, 2].map((k) => {
const g = top[k] const g = top[k]
return ( return (
@@ -99,13 +99,13 @@ export function GakPage() {
key={g.index_id} key={g.index_id}
type="button" type="button"
onClick={() => open({ type: 'gak', indexId: g.index_id })} onClick={() => open({ type: 'gak', indexId: g.index_id })}
className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'bg-white py-3')} className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'mt-6 bg-white py-3')}
> >
<span className="relative"> <span className="relative">
<Ic name={g.icon} className={cx('drop-shadow-[0_10px_12px_rgb(40_48_74/0.15)]', k === 0 ? 'w-20' : 'w-[62px]')} /> <Ic name={g.icon} className={cx('drop-shadow-[0_10px_12px_rgb(40_48_74/0.15)]', k === 0 ? 'w-20' : 'w-[62px]')} />
<Ic name={MEDALS[k]} className="absolute -top-1.5 -left-3 w-7" /> <Ic name={MEDALS[k]} className="absolute -top-1.5 -left-3 w-7" />
</span> </span>
<b className="mt-1.5 font-jua text-base font-normal"> <b className="mt-1.5 flex flex-1 items-center font-jua text-base font-normal">
{k + 1}위 {g.name} {k + 1}위 {g.name}
</b> </b>
<em className="font-bagel text-[30px] leading-[1.05] text-(--orange) not-italic">{g.score}</em> <em className="font-bagel text-[30px] leading-[1.05] text-(--orange) not-italic">{g.score}</em>
+3 -1
View File
@@ -130,7 +130,9 @@ function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) {
const top1 = slotTop ?? hero?.top1 const top1 = slotTop ?? hero?.top1
// 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다 // 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다
const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null
const bubble = slotTop ? (slotTop.score >= 70 ? `오늘은 ${slotTop.name}!` : '오늘은 쉬어 가요') : hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null // 말풍선 머리말은 칸 이름 그대로: 지금은 / 아침은 / 낮은 / 저녁은 / 밤은
const when = mode === 'now' || mode === nowKind ? '지금' : PREVIEW[mode].label
const bubble = slotTop ? (slotTop.score >= 70 ? `${when}은 ${slotTop.name}!` : `${when}은 쉬어 가요`) : hero ? (hero.bubble ?? '지금은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null
const status = hero?.status ?? [] const status = hero?.status ?? []
const rain = weather === 'rain' || weather === 'sleet' const rain = weather === 'rain' || weather === 'sleet'
const snow = weather === 'snow' || weather === 'sleet' const snow = weather === 'snow' || weather === 'sleet'
+1 -1
View File
@@ -1,6 +1,6 @@
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay']) const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang', 'baseball', 'study', 'netflix', 'chestnut', 'peanut', 'tangerine', 'sweet_potato', 'fallen_leaf', 'kimchi', 'apple', 'mask', 'golf', 'jipkok', 'fishing', 'drive', 'kite', 'waterplay', 'riverwind', 'trot', 'pajeon', 'bingsu', 'blanket', 'indoordry', 'flower', 'bungeoppang', 'singing_rain'])
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert']) const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf', 'popup', 'exhibition', 'concert'])
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */ /** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons). 'none'(데이터 없는 칸)은 그림 없음 */
+49 -2
View File
@@ -1,3 +1,15 @@
import com.google.android.wearable.watchface.validator.client.DwfValidatorFactory
// 스킨 APK 검증·토큰 발급기 (Watch Face Push). 의존성 하나가 jitpack 에만 있다
buildscript {
repositories {
google()
mavenCentral()
maven("https://jitpack.io") { content { includeGroup("com.github.xgouchet") } }
}
dependencies { classpath("com.google.android.wearable.watchface.validator:validator-push:1.0.0-alpha09") }
}
plugins { plugins {
id("com.android.application") id("com.android.application")
id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.compose")
@@ -9,10 +21,13 @@ android {
defaultConfig { defaultConfig {
applicationId = "kr.o2o.nalssigak" applicationId = "kr.o2o.nalssigak"
minSdk = 30 // Wear OS 6+ 만. 앱 설치 때 스킨을 같이 깔고 시계 화면으로 바꾸는 Watch Face Push 가 API 36 부터다
targetSdk = 34 minSdk = 36
targetSdk = 36
versionCode = 1 versionCode = 1
versionName = "0.1" versionName = "0.1"
// 앱에 실은 스킨 버전. 워치에 깔린 스킨이 이보다 낮으면 앱이 바꿔 끼운다 (MainActivity.useSkin)
buildConfigField("int", "SKIN_VERSION", providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get())
} }
buildTypes { buildTypes {
// 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810) // 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810)
@@ -38,4 +53,36 @@ dependencies {
implementation("androidx.wear.tiles:tiles:1.6.2") implementation("androidx.wear.tiles:tiles:1.6.2")
implementation("androidx.concurrent:concurrent-futures:1.3.0") implementation("androidx.concurrent:concurrent-futures:1.3.0")
implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.3.0") implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.3.0")
implementation("androidx.wear.watchfacepush:watchfacepush:1.0.0")
}
// 앱을 깔면 스킨(:watchface)도 같이 깔리게 한다 (Wear OS 6+ 기본 워치 페이스).
// 같은 빌드 타입의 스킨 APK 를 assets/default_watchface.apk 로 싣고, 검증 토큰을 문자열 리소스로 만든다
androidComponents.onVariants { variant ->
val name = variant.name.replaceFirstChar(Char::titlecase)
val skinApks = project(":watchface").layout.buildDirectory.dir("outputs/apk/${variant.name}")
val assetsDir = layout.buildDirectory.dir("generated/skinAssets/${variant.name}")
val resDir = layout.buildDirectory.dir("generated/skinToken/${variant.name}")
val appId = variant.applicationId
variant.sources.assets?.addStaticSourceDirectory(assetsDir.get().asFile.path)
variant.sources.res?.addStaticSourceDirectory(resDir.get().asFile.path)
val bundle = tasks.register("bundleSkin$name") {
dependsOn(":watchface:assemble$name")
inputs.dir(skinApks)
outputs.dirs(assetsDir, resDir)
doLast {
val apk = skinApks.get().asFile.listFiles { f -> f.extension == "apk" }!!.single()
// 서명 없는 스킨은 워치가 설치를 거부한다. 업로드 키 설정은 루트 build.gradle.kts 참고
if (apk.name.endsWith("-unsigned.apk")) throw GradleException("스킨 APK 가 서명되지 않았습니다. ~/.gradle/gradle.properties 에 NALSSIGAK_STORE_* 를 넣고 다시 빌드하세요")
val result = DwfValidatorFactory.create().validate(apk, appId.get())
if (result.failures().isNotEmpty()) throw GradleException("스킨 검증 실패: ${result.failures()}")
apk.copyTo(assetsDir.get().file("default_watchface.apk").asFile, overwrite = true)
resDir.get().file("values/skin_token.xml").asFile.apply { parentFile.mkdirs() }
.writeText(
"""<resources xmlns:tools="http://schemas.android.com/tools">""" +
"""<string name="default_wf_token" translatable="false" tools:ignore="Typos">${result.validationToken()}</string></resources>""" + "\n"
)
}
}
afterEvaluate { tasks.named("pre${name}Build") { dependsOn(bundle) } }
} }
+10 -2
View File
@@ -4,6 +4,9 @@
<uses-feature android:name="android.hardware.type.watch" /> <uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 앱과 같이 깔리는 날씨각 스킨을 시계 화면으로 바꾸는 권한 (Watch Face Push) -->
<uses-permission android:name="com.google.wear.permission.PUSH_WATCH_FACES" />
<uses-permission android:name="com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE" />
<application <application
android:icon="@drawable/ic_gak" android:icon="@drawable/ic_gak"
@@ -13,6 +16,11 @@
<!-- 폰 앱 없이 워치에서 단독으로 동작 --> <!-- 폰 앱 없이 워치에서 단독으로 동작 -->
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" /> <meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
<!-- 앱 설치 때 assets/default_watchface.apk(스킨)도 같이 설치된다. 토큰은 빌드가 만든다 (build.gradle.kts) -->
<meta-data
android:name="com.google.android.wearable.marketplace.DEFAULT_WATCHFACE_VALIDATION_TOKEN"
android:value="@string/default_wf_token" />
<activity android:name=".MainActivity" android:exported="true" android:taskAffinity=""> <activity android:name=".MainActivity" android:exported="true" android:taskAffinity="">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
@@ -126,7 +134,7 @@
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" /> <meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
</service> </service>
<!-- 워치 스킨 숨은 칸용: 비·눈 여부 --> <!-- 워치 스킨 숨은 칸용: 날씨(비·눈·천둥)·기온·가운데 1위 -->
<service <service
android:name=".RainComplicationService" android:name=".RainComplicationService"
android:exported="true" android:exported="true"
@@ -136,7 +144,7 @@
<intent-filter> <intent-filter>
<action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" /> <action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />
</intent-filter> </intent-filter>
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="SHORT_TEXT" /> <meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="RANGED_VALUE" />
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" /> <meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
</service> </service>
@@ -3,6 +3,8 @@ package kr.o2o.nalssigak
import android.Manifest import android.Manifest
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
@@ -16,29 +18,85 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.lifecycle.lifecycleScope
import androidx.wear.compose.foundation.pager.VerticalPager import androidx.wear.compose.foundation.pager.VerticalPager
import androidx.wear.compose.foundation.pager.rememberPagerState import androidx.wear.compose.foundation.pager.rememberPagerState
import androidx.wear.compose.material3.MaterialTheme import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.VerticalPageIndicator import androidx.wear.compose.material3.VerticalPageIndicator
import androidx.wear.watchfacepush.WatchFacePushManager
import androidx.wear.watchfacepush.WatchFacePushManagerFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.time.Instant import java.time.Instant
import kotlin.concurrent.thread import kotlin.concurrent.thread
/** 컴플리케이션 탭이 실어 보내는 각 코드 */ /** 컴플리케이션 탭이 실어 보내는 각 코드 */
const val EXTRA_GAK = "gak" const val EXTRA_GAK = "gak"
/** 앱과 같이 깔린 스킨을 시계 화면으로 바꾸는 권한. 사용자가 한 번 거절하면 다시 묻지 못한다 */
private const val SET_SKIN = "com.google.wear.permission.SET_PUSHED_WATCH_FACE_AS_ACTIVE"
private const val TAG = "MainActivity"
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
private var summary by mutableStateOf<Summary?>(null) private var summary by mutableStateOf<Summary?>(null)
private var loading by mutableStateOf(true) private var loading by mutableStateOf(true)
private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() } private val askPermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
load()
useSkin()
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
val opened = intent.getStringExtra(EXTRA_GAK) val opened = intent.getStringExtra(EXTRA_GAK)
setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } } setContent { MaterialTheme { App(summary, loading, opened) { load(force = true) } } }
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load() // 위치와 스킨 적용을 한 번에 묻는다
else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION) val missing = listOf(Manifest.permission.ACCESS_COARSE_LOCATION, SET_SKIN).filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
if (missing.isEmpty()) {
load()
useSkin()
} else askPermissions.launch(missing.toTypedArray())
}
/**
* 앱 설치 때 같이 깔린 날씨각 스킨을 챙긴다.
* 앱 업데이트로 새 스킨이 실려 왔으면 바꿔 끼우고(기본 스킨은 처음 설치 때만 깔린다), 허락받았으면 시계 화면으로 바꾼다(시스템이 앱마다 한 번만 허락한다).
*/
private fun useSkin() {
lifecycleScope.launch {
val push = WatchFacePushManagerFactory.createWatchFacePushManager(this@MainActivity)
try {
// 기본 스킨 설치가 아직 안 끝났으면 다음 실행 때 다시 본다
val skin = push.listWatchFaces().installedWatchFaceDetails.firstOrNull() ?: return@launch
if (skin.versionCode < BuildConfig.SKIN_VERSION) updateSkin(push, skin.slotId)
if (checkSelfPermission(SET_SKIN) == PackageManager.PERMISSION_GRANTED && !push.isWatchFaceActive(skin.packageName)) {
push.setWatchFaceAsActive(skin.slotId)
}
} catch (e: WatchFacePushManager.ListWatchFacesException) {
Log.w(TAG, "스킨 목록을 못 읽음", e)
} catch (e: WatchFacePushManager.UpdateWatchFaceException) {
Log.w(TAG, "스킨을 새 버전으로 못 바꿈", e)
} catch (e: WatchFacePushManager.IsWatchFaceActiveException) {
Log.w(TAG, "스킨 사용 여부를 못 읽음", e)
} catch (e: WatchFacePushManager.SetWatchFaceAsActiveException) {
// 이미 한 번 바꾼 뒤 사용자가 다른 화면으로 옮긴 경우. 다시 바꾸지 않는다
Log.i(TAG, "스킨을 시계 화면으로 바꾸지 않음", e)
}
}
}
/** 앱에 실은 스킨(assets/default_watchface.apk)으로 바꿔 끼운다. 검증 토큰은 빌드가 만든 것 (build.gradle.kts) */
private suspend fun updateSkin(push: WatchFacePushManager, slotId: String) {
val apk = File(cacheDir, "skin.apk")
try {
withContext(Dispatchers.IO) { assets.open("default_watchface.apk").use { input -> apk.outputStream().use { input.copyTo(it) } } }
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { push.updateWatchFace(slotId, it, getString(R.string.default_wf_token)) }
} finally {
apk.delete()
}
} }
private fun load(force: Boolean = false) { private fun load(force: Boolean = false) {
@@ -50,7 +108,7 @@ class MainActivity : ComponentActivity() {
} }
} }
private enum class Page { DETAIL, EVENTS, TOP, PICKS, SUNSET, HOURS } private enum class Page { DETAIL, HOURS, EVENTS, TOP, PICKS, SUNSET }
@Composable @Composable
private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) { private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) {
@@ -65,15 +123,15 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U
StatePage(loading, onRetry) StatePage(loading, onRetry)
return return
} }
// 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 주변 축제부터 (축제가 없으면 오늘의 각부터) // 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 오늘 남은 시간 → 주변 축제 → 각 순서
val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } } val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } }
val pages = buildList { val pages = buildList {
if (detail != null) add(Page.DETAIL) if (detail != null) add(Page.DETAIL)
if (s.slots.isNotEmpty()) add(Page.HOURS)
if (s.events.isNotEmpty()) add(Page.EVENTS) if (s.events.isNotEmpty()) add(Page.EVENTS)
if (s.top.isNotEmpty()) add(Page.TOP) if (s.top.isNotEmpty()) add(Page.TOP)
if (s.picks.isNotEmpty()) add(Page.PICKS) if (s.picks.isNotEmpty()) add(Page.PICKS)
if (s.sunset != null) add(Page.SUNSET) if (s.sunset != null) add(Page.SUNSET)
if (s.slots.isNotEmpty()) add(Page.HOURS)
} }
val state = rememberPagerState { pages.size } val state = rememberPagerState { pages.size }
Box(Modifier.fillMaxSize()) { Box(Modifier.fillMaxSize()) {
@@ -1,27 +1,45 @@
package kr.o2o.nalssigak package kr.o2o.nalssigak
import android.app.PendingIntent
import android.content.Intent
import androidx.wear.watchface.complications.data.ComplicationData import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.ComplicationType import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.PlainComplicationText import androidx.wear.watchface.complications.data.PlainComplicationText
import androidx.wear.watchface.complications.data.ShortTextComplicationData import androidx.wear.watchface.complications.data.RangedValueComplicationData
import androidx.wear.watchface.complications.datasource.ComplicationRequest import androidx.wear.watchface.complications.datasource.ComplicationRequest
import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.math.roundToInt import kotlin.math.roundToInt
/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"천둥 쳐요"·"눈 와요")을 보고 빗줄기·눈송이와 가운데 구름도 그린다. */ /**
* 워치 스킨 날씨 칸 + 가운데 1위. 스킨 칸이 8개까지라 한 칸에 몰아 준다.
* 값 = 날씨 코드(0 맑음·1 비·2 천둥·3 눈) × 1000 + 1위 점수, 글자 = 지금 기온, 제목 = 1위 이름(없으면 빈 글자).
*/
class RainComplicationService : SuspendingComplicationDataSourceService() { class RainComplicationService : SuspendingComplicationDataSourceService() {
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? {
val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null
return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel) val code = when (s.rainLabel) {
"비 와요", "곧 비" -> 1
"천둥 쳐요" -> 2
"눈 와요" -> 3
else -> 0
}
val top = s.top.firstOrNull()
return data(code, top?.score ?: 0, s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", top?.name ?: "")
} }
override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음") override fun getPreviewData(type: ComplicationType): ComplicationData = data(0, 88, "20°", "산책각")
private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder( private fun data(code: Int, score: Int, temp: String, name: String): ComplicationData {
PlainComplicationText.Builder(temp).build(), // 가운데 구슬을 누르면 앱 첫 장
PlainComplicationText.Builder("$temp $rain").build(), val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java)
).setTitle(PlainComplicationText.Builder(rain).build()).build() .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return RangedValueComplicationData.Builder(code * 1000f + score, 0f, 3100f, PlainComplicationText.Builder("$name $score, $temp").build())
.setText(PlainComplicationText.Builder(temp).build())
.setTitle(PlainComplicationText.Builder(name).build())
.setTapAction(open)
.build()
}
} }
@@ -186,7 +186,7 @@ fun EventsPage(events: List<Event>, now: Instant) {
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
) { ) {
T("근처 축제", 14.sp, color = Tok.ink) T("주변 축제", 14.sp, color = Tok.ink)
events.forEach { e -> events.forEach { e ->
Column(Modifier.fillMaxWidth().mallang().padding(start = 10.dp, end = 10.dp, top = 5.dp, bottom = 8.dp)) { Column(Modifier.fillMaxWidth().mallang().padding(start = 10.dp, end = 10.dp, top = 5.dp, bottom = 8.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) { Row(verticalAlignment = Alignment.CenterVertically) {
@@ -60,7 +60,7 @@ data class Summary(
else -> null else -> null
} }
/** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */ /** 비 소식. 스킨 날씨 칸(RainComplicationService)이 이 글자로 날씨 코드를 정한다 */
val rainLabel: String get() = when { val rainLabel: String get() = when {
precip == "snow" -> "눈 와요" precip == "snow" -> "눈 와요"
thunder == true -> "천둥 쳐요" thunder == true -> "천둥 쳐요"
@@ -48,6 +48,9 @@ private val ICONS = mapOf(
"glasses" to R.drawable.e_glasses, "makeup" to R.drawable.e_makeup, "naengmyeon" to R.drawable.e_naengmyeon, "taxi" to R.drawable.e_taxi, "glasses" to R.drawable.e_glasses, "makeup" to R.drawable.e_makeup, "naengmyeon" to R.drawable.e_naengmyeon, "taxi" to R.drawable.e_taxi,
"delivery" to R.drawable.e_delivery, "garden" to R.drawable.e_garden, "photo" to R.drawable.e_photo, "baseball" to R.drawable.e_baseball, "delivery" to R.drawable.e_delivery, "garden" to R.drawable.e_garden, "photo" to R.drawable.e_photo, "baseball" to R.drawable.e_baseball,
"study" to R.drawable.e_study, "netflix" to R.drawable.e_netflix, "chestnut" to R.drawable.e_chestnut, "study" to R.drawable.e_study, "netflix" to R.drawable.e_netflix, "chestnut" to R.drawable.e_chestnut,
"drive" to R.drawable.e_drive, "fishing" to R.drawable.e_fishing, "golf" to R.drawable.e_golf, "jipkok" to R.drawable.e_jipkok,
"kimchi" to R.drawable.e_kimchi, "kite" to R.drawable.e_kite, "maple" to R.drawable.e_maple, "sheaf" to R.drawable.e_sheaf,
"sweet_potato" to R.drawable.e_sweet_potato, "tangerine" to R.drawable.e_tangerine, "waterplay" to R.drawable.e_waterplay,
"sun" to R.drawable.e_sun, "sun_cloud" to R.drawable.e_sun_cloud, "cloud" to R.drawable.e_cloud, "rain" to R.drawable.e_rain, "sun" to R.drawable.e_sun, "sun_cloud" to R.drawable.e_sun_cloud, "cloud" to R.drawable.e_cloud, "rain" to R.drawable.e_rain,
"snow" to R.drawable.e_snow, "sunset" to R.drawable.e_sunset, "moon" to R.drawable.e_moon, "snow" to R.drawable.e_snow, "sunset" to R.drawable.e_sunset, "moon" to R.drawable.e_moon,
"gold" to R.drawable.e_gold, "silver" to R.drawable.e_silver, "bronze" to R.drawable.e_bronze, "gold" to R.drawable.e_gold, "silver" to R.drawable.e_silver, "bronze" to R.drawable.e_bronze,
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+2
View File
@@ -1,2 +1,4 @@
org.gradle.jvmargs=-Xmx2g org.gradle.jvmargs=-Xmx2g
android.useAndroidX=true android.useAndroidX=true
# 워치 스킨 버전. 스킨(watchface.xml·리소스)을 바꾸면 1 올린다. 앱은 깔린 스킨이 이보다 낮으면 앱에 실은 스킨으로 바꿔 끼운다
NALSSIGAK_SKIN_VERSION=2
+5 -4
View File
@@ -9,15 +9,16 @@ android {
compileSdk = 37 compileSdk = 37
defaultConfig { defaultConfig {
applicationId = "kr.o2o.nalssigak.watchface" // 앱(:app)이 Watch Face Push 로 같이 설치하려면 "<앱 패키지>.watchfacepush.<이름>" 이어야 한다
applicationId = "kr.o2o.nalssigak.watchfacepush.skin"
// WFF 버전 2 는 Wear OS 5(API 34)부터 // WFF 버전 2 는 Wear OS 5(API 34)부터
minSdk = 34 minSdk = 34
targetSdk = 34 targetSdk = 34
versionCode = 1 versionCode = providers.gradleProperty("NALSSIGAK_SKIN_VERSION").get().toInt()
versionName = "0.1" versionName = "0.1"
} }
buildTypes.getByName("release") { // 스킨 APK 엔 dex 가 없어야 한다 (Play 번들, 앱에 싣는 Watch Face Push 둘 다). R8 이 R 클래스까지 다 걷어내게
// 스킨 번들엔 dex 가 없어야 한다. R8 이 R 클래스까지 다 걷어내게 buildTypes.all {
isMinifyEnabled = true isMinifyEnabled = true
// 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것 // 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것
isShrinkResources = false isShrinkResources = false
+27 -28
View File
@@ -117,21 +117,19 @@ def text(x, y, w, h, family, size, color, expr, amb=False):
<Text align="CENTER" ellipsis="TRUE"><Font family="{family}" size="{size}" color="{color}"><Template><![CDATA[%s]]><Parameter expression="{expr}"/></Template></Font></Text> <Text align="CENTER" ellipsis="TRUE"><Font family="{family}" size="{size}" color="{color}"><Template><![CDATA[%s]]><Parameter expression="{expr}"/></Template></Font></Text>
</PartText>''' </PartText>'''
def orb_slot(): def orb_text():
"""해 구슬 위 1위 점수·이름. 날씨 칸 값: 값 = 날씨 코드 × 1000 + 1위 점수, 제목 = 1위 이름 (1위가 없으면 빈 제목)"""
x, y = CX - ORB // 2, CY - ORB // 2 x, y = CX - ORB // 2, CY - ORB // 2
body = text(0, int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]") body = (text(x, y + int(ORB * .19), ORB, int(ORB * .45), "bagel_fat_one", 50, "#FFFFFFFF", f"round({VALUE} % 1000)")
return f'''<ComplicationSlot slotId="0" x="{x}" y="{y}" width="{ORB}" height="{ORB}" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE"> + text(x + 14, y + int(ORB * .62), ORB - 28, 28, "jua", 19, "#FFFFFFFF", "[COMPLICATION.TITLE]"))
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/> return f'''<Condition>
<BoundingOval x="0" y="0" width="{ORB}" height="{ORB}"/> <Expressions><Expression name="ranked"><![CDATA[[COMPLICATION.TITLE] != ""]]></Expression></Expressions>
<Complication type="RANGED_VALUE"> <Compare expression="ranked">
{body} {body}
</Complication> </Compare>
<Complication type="SHORT_TEXT"> </Condition>'''
{body}
</Complication>
<Complication type="EMPTY"/>
</ComplicationSlot>'''
VALUE = "[COMPLICATION.RANGED_VALUE_VALUE]"
PROGRESS = "clamp([COMPLICATION.RANGED_VALUE_VALUE], [COMPLICATION.RANGED_VALUE_MIN], [COMPLICATION.RANGED_VALUE_MAX]) / ([COMPLICATION.RANGED_VALUE_MAX] - [COMPLICATION.RANGED_VALUE_MIN]) * 360" PROGRESS = "clamp([COMPLICATION.RANGED_VALUE_VALUE], [COMPLICATION.RANGED_VALUE_MIN], [COMPLICATION.RANGED_VALUE_MAX]) / ([COMPLICATION.RANGED_VALUE_MAX] - [COMPLICATION.RANGED_VALUE_MIN]) * 360"
def icon_by_title(x, y, size): def icon_by_title(x, y, size):
@@ -182,10 +180,11 @@ def chip(x, w, icon, expr):
{text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}''' {text(x + 32, CHIP_Y + 5, w - 38, 30, "jua", 21, INK, expr, amb=True)}'''
def precip_slot(): def precip_slot():
"""화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면 """화면 전체를 덮는 숨은 칸. WFF 는 칸이 8개까지라 날씨와 1위를 이 칸 하나로 받는다.
아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기와 비구름, "천둥 쳐요"면 빗줄기와 번개 구름, 날씨각 앱(RainComplicationService)이 값 = 날씨 코드 × 1000 + 1위 점수, 글자 = 기온, 제목 = 1위 이름을 준다.
"눈 와요"면 눈송이와 눈구름을 가운데 해 자리에 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다. 날씨 코드 1(비·곧 비)이면 빗줄기와 비구름, 2(천둥)면 빗줄기와 번개 구름, 3(눈)이면 눈송이와 눈구름을 가운데 해 자리에 그리고,
터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" 그 위에 1위 점수·이름, 아래에 기온 칩을 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다.
터치는 가운데 구슬만 받는다(누르면 앱). 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다."""
import random import random
r = random.Random(7) r = random.Random(7)
drops, flakes = [], [] drops, flakes = [], []
@@ -207,15 +206,16 @@ def precip_slot():
<Transform target="x" value="{x} + 9 * sin(rad(360 * fract([SECOND_MILLISECOND] / 3 + {ph:.2f})))"/> <Transform target="x" value="{x} + 9 * sin(rad(360 * fract([SECOND_MILLISECOND] / 3 + {ph:.2f})))"/>
</PartDraw>''') </PartDraw>''')
shade = lambda c: f'<PartDraw x="0" y="0" width="{W}" height="{W}">{AMB0}<Rectangle x="0" y="0" width="{W}" height="{W}"><Fill color="{c}"/></Rectangle></PartDraw>' shade = lambda c: f'<PartDraw x="0" y="0" width="{W}" height="{W}">{AMB0}<Rectangle x="0" y="0" width="{W}" height="{W}"><Fill color="{c}"/></Rectangle></PartDraw>'
return f'''<ComplicationSlot slotId="7" x="0" y="0" width="{W}" height="{W}" displayName="slot_precip" supportedTypes="SHORT_TEXT EMPTY" isCustomizable="FALSE"> mode = f"floor({VALUE} / 1000)"
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.RainComplicationService" primaryProviderType="SHORT_TEXT"/> return f'''<ComplicationSlot slotId="7" x="0" y="0" width="{W}" height="{W}" displayName="slot_precip" supportedTypes="RANGED_VALUE EMPTY" isCustomizable="FALSE">
<BoundingOval x="0" y="0" width="1" height="1"/> <DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="{APP}/{APP}.RainComplicationService" primaryProviderType="RANGED_VALUE"/>
<Complication type="SHORT_TEXT"> <BoundingOval x="0" y="0" width="{W}" height="{W}"/>
<Complication type="RANGED_VALUE">
<Condition> <Condition>
<Expressions> <Expressions>
<Expression name="thunder"><![CDATA[[COMPLICATION.TITLE] == "천둥 쳐요"]]></Expression> <Expression name="thunder"><![CDATA[{mode} == 2]]></Expression>
<Expression name="rain"><![CDATA[[COMPLICATION.TITLE] == "비 와요" || [COMPLICATION.TITLE] == "곧 비"]]></Expression> <Expression name="rain"><![CDATA[{mode} == 1]]></Expression>
<Expression name="snow"><![CDATA[[COMPLICATION.TITLE] == "눈 와요"]]></Expression> <Expression name="snow"><![CDATA[{mode} == 3]]></Expression>
<Expression name="night"><![CDATA[{NIGHT_EXPR}]]></Expression> <Expression name="night"><![CDATA[{NIGHT_EXPR}]]></Expression>
</Expressions> </Expressions>
<Compare expression="thunder"> <Compare expression="thunder">
@@ -235,8 +235,8 @@ def precip_slot():
</Compare> </Compare>
{sun_or_moon()} {sun_or_moon()}
</Condition> </Condition>
{chip(108, 104, "thermo", "[COMPLICATION.TEXT]")} {chip(CX - 52, 104, "thermo", "[COMPLICATION.TEXT]")}
{chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")} {orb_text()}
</Complication> </Complication>
<Complication type="EMPTY"> <Complication type="EMPTY">
<Condition> <Condition>
@@ -258,7 +258,7 @@ def event_slot():
<RoundRectangle x="0" y="0" width="{w}" height="{h}" cornerRadiusX="{h // 2}" cornerRadiusY="{h // 2}"><Fill color="{CARD}"/></RoundRectangle> <RoundRectangle x="0" y="0" width="{w}" height="{h}" cornerRadiusX="{h // 2}" cornerRadiusY="{h // 2}"><Fill color="{CARD}"/></RoundRectangle>
</PartDraw> </PartDraw>
<PartText x="8" y="2" width="{w - 16}" height="{h - 4}">{AMB0} <PartText x="8" y="2" width="{w - 16}" height="{h - 4}">{AMB0}
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="{INK}"><Template><![CDATA[🎉 주변 축제 · %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text> <Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="{INK}"><Template><![CDATA[🎉 주변 축제: %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
</PartText> </PartText>
</Complication> </Complication>
<Complication type="EMPTY"/> <Complication type="EMPTY"/>
@@ -273,7 +273,7 @@ exprs = "\n ".join(f'<Expression name="{k}"><![CDATA[{v[0].replace("&gt
compares = "\n ".join(f'<Compare expression="{k}">\n {mode_block(v[1], v[2], v[3])}\n </Compare>' for k, v in MODES.items()) compares = "\n ".join(f'<Compare expression="{k}">\n {mode_block(v[1], v[2], v[3])}\n </Compare>' for k, v in MODES.items())
xml = f'''<?xml version="1.0" encoding="UTF-8"?> xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위, 비·눈·천둥이면 구름), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다. <!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위, 비·눈·천둥이면 구름), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml --> 직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml -->
<WatchFace width="{W}" height="{W}"> <WatchFace width="{W}" height="{W}">
<Metadata key="CLOCK_TYPE" value="DIGITAL"/> <Metadata key="CLOCK_TYPE" value="DIGITAL"/>
@@ -293,7 +293,6 @@ xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 --> <!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 -->
{precip_slot()} {precip_slot()}
{clock("#FFFFFFFF", ambient_visible=True)} {clock("#FFFFFFFF", ambient_visible=True)}
{orb_slot()}
{"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))} {"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))}
{event_slot()} {event_slot()}
</Scene> </Scene>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+21 -38
View File
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위, 비·눈·천둥이면 구름), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온·비 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다. <!-- 날씨각 워치 스킨: 시간대 하늘, 해 구슬(1위, 비·눈·천둥이면 구름), 둘레 링(2~7위), 날짜 밑 근처 축제 한 줄, 아래 기온 칩. 링을 누르면 앱이 그 각 상세로 열린다. 점수는 날씨각 앱의 RankNComplicationService 가 공급한다.
직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml --> 직접 고치지 말고 watch/watchface/gen_watchface.py 를 고친 뒤 다시 만든다: python3 gen_watchface.py src/main/res/raw/watchface.xml -->
<WatchFace width="450" height="450"> <WatchFace width="450" height="450">
<Metadata key="CLOCK_TYPE" value="DIGITAL"/> <Metadata key="CLOCK_TYPE" value="DIGITAL"/>
@@ -148,15 +148,15 @@
</Condition> </Condition>
<!-- 주의: 칸(ComplicationSlot) 순서·slotId 를 바꿔 덮어 설치하면 기존 기기에서 공급원이 한 칸씩 밀린다 (에뮬레이터에서 확인). 새 칸은 맨 뒤에 붙인다 --> <!-- 주의: 칸(ComplicationSlot) 순서·slotId 를 바꿔 덮어 설치하면 기존 기기에서 공급원이 한 칸씩 밀린다 (에뮬레이터에서 확인). 새 칸은 맨 뒤에 붙인다 -->
<!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 --> <!-- 가운데 해·달·구름은 날씨 칸 안에서 비 막 위에 그린다 -->
<ComplicationSlot slotId="7" x="0" y="0" width="450" height="450" displayName="slot_precip" supportedTypes="SHORT_TEXT EMPTY" isCustomizable="FALSE"> <ComplicationSlot slotId="7" x="0" y="0" width="450" height="450" displayName="slot_precip" supportedTypes="RANGED_VALUE EMPTY" isCustomizable="FALSE">
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.RainComplicationService" primaryProviderType="SHORT_TEXT"/> <DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.RainComplicationService" primaryProviderType="RANGED_VALUE"/>
<BoundingOval x="0" y="0" width="1" height="1"/> <BoundingOval x="0" y="0" width="450" height="450"/>
<Complication type="SHORT_TEXT"> <Complication type="RANGED_VALUE">
<Condition> <Condition>
<Expressions> <Expressions>
<Expression name="thunder"><![CDATA[[COMPLICATION.TITLE] == "천둥 쳐요"]]></Expression> <Expression name="thunder"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 2]]></Expression>
<Expression name="rain"><![CDATA[[COMPLICATION.TITLE] == "비 와요" || [COMPLICATION.TITLE] == "곧 비"]]></Expression> <Expression name="rain"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 1]]></Expression>
<Expression name="snow"><![CDATA[[COMPLICATION.TITLE] == "눈 와요"]]></Expression> <Expression name="snow"><![CDATA[floor([COMPLICATION.RANGED_VALUE_VALUE] / 1000) == 3]]></Expression>
<Expression name="night"><![CDATA[[HOUR_0_23] < 5 || [HOUR_0_23] >= 21]]></Expression> <Expression name="night"><![CDATA[[HOUR_0_23] < 5 || [HOUR_0_23] >= 21]]></Expression>
</Expressions> </Expressions>
<Compare expression="thunder"> <Compare expression="thunder">
@@ -495,22 +495,24 @@
<Ellipse x="16" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse><Ellipse x="97" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse> <Ellipse x="16" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse><Ellipse x="97" y="84" width="21" height="12"><Fill color="#73FF7A8A"/></Ellipse>
</PartDraw></Default> </PartDraw></Default>
</Condition> </Condition>
<PartDraw x="108" y="366" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/> <PartDraw x="173" y="366" width="104" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/>
<RoundRectangle x="0" y="0" width="104" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle> <RoundRectangle x="0" y="0" width="104" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle>
<RoundRectangle x="0" y="35" width="104" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle> <RoundRectangle x="0" y="35" width="104" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle>
</PartDraw> </PartDraw>
<PartImage x="116" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage> <PartImage x="181" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_thermo"/></PartImage>
<PartText x="140" y="371" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/> <PartText x="205" y="371" width="66" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/>
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text> <Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
</PartText> </PartText>
<PartDraw x="220" y="366" width="122" height="40"><Variant mode="AMBIENT" target="alpha" value="0"/> <Condition>
<RoundRectangle x="0" y="0" width="122" height="40" cornerRadiusX="20" cornerRadiusY="20"><Fill color="#B8FFFFFF"/></RoundRectangle> <Expressions><Expression name="ranked"><![CDATA[[COMPLICATION.TITLE] != ""]]></Expression></Expressions>
<RoundRectangle x="0" y="35" width="122" height="5" cornerRadiusX="2" cornerRadiusY="2"><Fill color="#E6D9E5F4"/></RoundRectangle> <Compare expression="ranked">
</PartDraw> <PartText x="157" y="209" width="136" height="61">
<PartImage x="228" y="372" width="26" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/><Image resource="e_umbrella"/></PartImage> <Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="round([COMPLICATION.RANGED_VALUE_VALUE] % 1000)"/></Template></Font></Text>
<PartText x="252" y="371" width="84" height="30"><Variant mode="AMBIENT" target="alpha" value="0"/> </PartText><PartText x="171" y="268" width="108" height="28">
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="21" color="#FF28304A"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text> <Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
</PartText> </PartText>
</Compare>
</Condition>
</Complication> </Complication>
<Complication type="EMPTY"> <Complication type="EMPTY">
<Condition> <Condition>
@@ -535,25 +537,6 @@
<Font family="bagel_fat_one" size="68" color="#FFFFFFFF"/> <Font family="bagel_fat_one" size="68" color="#FFFFFFFF"/>
</TimeText> </TimeText>
</DigitalClock> </DigitalClock>
<ComplicationSlot slotId="0" x="157" y="184" width="136" height="136" displayName="slot_rank1" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank1ComplicationService" primaryProviderType="RANGED_VALUE"/>
<BoundingOval x="0" y="0" width="136" height="136"/>
<Complication type="RANGED_VALUE">
<PartText x="0" y="25" width="136" height="61">
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
</PartText><PartText x="14" y="84" width="108" height="28">
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
</PartText>
</Complication>
<Complication type="SHORT_TEXT">
<PartText x="0" y="25" width="136" height="61">
<Text align="CENTER" ellipsis="TRUE"><Font family="bagel_fat_one" size="50" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
</PartText><PartText x="14" y="84" width="108" height="28">
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="19" color="#FFFFFFFF"><Template><![CDATA[%s]]><Parameter expression="[COMPLICATION.TITLE]"/></Template></Font></Text>
</PartText>
</Complication>
<Complication type="EMPTY"/>
</ComplicationSlot>
<ComplicationSlot slotId="1" x="71" y="149" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE"> <ComplicationSlot slotId="1" x="71" y="149" width="68" height="68" displayName="slot_ring" supportedTypes="RANGED_VALUE SHORT_TEXT EMPTY" isCustomizable="TRUE">
<DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank2ComplicationService" primaryProviderType="RANGED_VALUE"/> <DefaultProviderPolicy defaultSystemProvider="EMPTY" defaultSystemProviderType="EMPTY" primaryProvider="kr.o2o.nalssigak/kr.o2o.nalssigak.Rank2ComplicationService" primaryProviderType="RANGED_VALUE"/>
<BoundingOval x="0" y="0" width="68" height="68"/> <BoundingOval x="0" y="0" width="68" height="68"/>
@@ -725,7 +708,7 @@
<RoundRectangle x="0" y="0" width="204" height="30" cornerRadiusX="15" cornerRadiusY="15"><Fill color="#B8FFFFFF"/></RoundRectangle> <RoundRectangle x="0" y="0" width="204" height="30" cornerRadiusX="15" cornerRadiusY="15"><Fill color="#B8FFFFFF"/></RoundRectangle>
</PartDraw> </PartDraw>
<PartText x="8" y="2" width="188" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/> <PartText x="8" y="2" width="188" height="26"><Variant mode="AMBIENT" target="alpha" value="0"/>
<Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="#FF28304A"><Template><![CDATA[🎉 주변 축제 · %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text> <Text align="CENTER" ellipsis="TRUE"><Font family="jua" size="17" color="#FF28304A"><Template><![CDATA[🎉 주변 축제: %s]]><Parameter expression="[COMPLICATION.TEXT]"/></Template></Font></Text>
</PartText> </PartText>
</Complication> </Complication>
<Complication type="EMPTY"/> <Complication type="EMPTY"/>