위젯별 투명도와 밝은·어두운 색상 및 글자 크기와 표시 항목을 추가했다. 모든 위젯에 함께 적용하는 기본값과 개별 설정을 구분하고 크기에 따라 배치를 바꾼다. 포럼에 APK와 전체 소스 및 사용법과 제작 매뉴얼을 함께 배포한다. 앱 단위 검사 34개와 서버 검사 63개 및 웹 날짜·업데이트 검사 통과. 공개 소스에서 APK 빌드와 정적 검사 오류 0개 확인. 경고는 69개다. Android 16 가상 기기에서 기존 앱 위에 설치하고 투명 위젯과 큰 글자 및 RemoteViews 검사를 확인했다. 실제 휴대폰과 다른 홈 화면 앱의 절전·크기 동작은 별도 확인이 필요하다. 회원 DB와 인증 정보 및 배포 서명 키와 내부 운영 기록은 공개 자료에 포함하지 않았다.
99 lines
5.2 KiB
Python
99 lines
5.2 KiB
Python
"""공개 공휴일 API의 정상 자료를 별도 DB에 보관한다. 회원 DB와 갱신 수명을 분리한다.
|
|
|
|
빈 응답과 일부 날짜만 담긴 응답은 저장하지 않는다. 통신 실패 때는 직전 정상 자료를
|
|
계속 제공한다. 서버는 하루마다 확인하지만 기기는 월별·수동·변경 확인 때만 전체 자료를 받는다.
|
|
"""
|
|
from contextlib import closing
|
|
from datetime import date
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from urllib.request import Request, urlopen
|
|
|
|
SOURCE = 'https://holidays.hyunbin.page/basic.json'
|
|
LIMIT = 1_048_576
|
|
|
|
|
|
def validate(raw, require_current=True):
|
|
if len(raw) > LIMIT:
|
|
raise ValueError('공휴일 응답 크기 초과')
|
|
data = json.loads(raw)
|
|
if not isinstance(data, dict) or not data:
|
|
raise ValueError('공휴일 연도 누락')
|
|
for year, days in data.items():
|
|
if not year.isdigit() or len(year) != 4 or not 2000 <= int(year) <= 2099 or not isinstance(days, dict) or not 15 <= len(days) <= 80:
|
|
raise ValueError('공휴일 연도 범위 또는 날짜 누락')
|
|
for key, names in days.items():
|
|
if str(date.fromisoformat(key).year) != year or not isinstance(names, list) or not 1 <= len(names) <= 8 or any(not isinstance(name, str) or not 1 <= len(name.strip()) <= 100 for name in names):
|
|
raise ValueError('공휴일 날짜 또는 이름 오류')
|
|
# 월력 자료가 중간에 잘려도 JSON 형식은 맞을 수 있다. 고정 공휴일과 두 명절을 함께 확인한다.
|
|
if any(f'{year}-{day}' not in days for day in ('01-01', '03-01', '05-05', '06-06', '08-15', '10-03', '10-09', '12-25')):
|
|
raise ValueError('고정 공휴일 누락')
|
|
names = [name for values in days.values() for name in values]
|
|
if sum('설날' in name for name in names) < 3 or sum('추석' in name for name in names) < 3:
|
|
raise ValueError('명절 자료 누락')
|
|
if require_current and str(date.today().year) not in data:
|
|
raise ValueError('올해 공휴일 누락')
|
|
return data
|
|
|
|
|
|
class HolidayStore:
|
|
def __init__(self, directory, bundled):
|
|
self.path = Path(directory) / 'holiday-cache.sqlite3'
|
|
self.gate = threading.Lock()
|
|
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
|
|
conn.execute('CREATE TABLE IF NOT EXISTS snapshot(id INTEGER PRIMARY KEY CHECK(id=1), body TEXT NOT NULL, revision TEXT NOT NULL, checked INTEGER NOT NULL, attempted INTEGER NOT NULL, saved INTEGER NOT NULL)')
|
|
if not conn.execute('SELECT 1 FROM snapshot').fetchone():
|
|
legacy = Path(directory) / 'holidays.json'
|
|
try:
|
|
data = validate(legacy.read_bytes(), False)
|
|
except Exception:
|
|
data = validate(Path(bundled).read_bytes(), False)
|
|
body = self.encode(data)
|
|
conn.execute('INSERT INTO snapshot VALUES(1,?,?,0,0,1)', (body, self.revision(body)))
|
|
self.path.chmod(0o600)
|
|
|
|
@staticmethod
|
|
def encode(data):
|
|
return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
|
|
|
@staticmethod
|
|
def revision(body):
|
|
return hashlib.sha256(body.encode()).hexdigest()[:24]
|
|
|
|
def read(self):
|
|
with closing(sqlite3.connect(self.path, timeout=10)) as conn:
|
|
body, revision, checked, attempted, saved = conn.execute('SELECT body,revision,checked,attempted,saved FROM snapshot WHERE id=1').fetchone()
|
|
return json.loads(body), {'revision': revision, 'checked': checked, 'attempted': attempted, 'saved': bool(saved)}
|
|
|
|
def refresh(self, force=False, fetch=None):
|
|
# 여러 수동 요청이 겹쳐도 외부 API는 한 번만 조회한다. 실패 시 재시도 간격은 1시간이다.
|
|
if not self.gate.acquire(blocking=False):
|
|
return False
|
|
try:
|
|
old, state = self.read()
|
|
now = int(time.time())
|
|
if now - state['attempted'] < 3600 or (not force and now - state['checked'] < 86400):
|
|
return not state['saved']
|
|
try:
|
|
if fetch is None:
|
|
with urlopen(Request(SOURCE, headers={'Accept': 'application/json', 'User-Agent': 'DutyCalendar/0.7 (+https://duty.itosm.co.kr/calendar/)'}), timeout=10) as response:
|
|
raw = response.read(LIMIT + 1)
|
|
else:
|
|
raw = fetch()
|
|
data = validate(raw)
|
|
# 제공처가 과거 연도를 목록에서 빼더라도 이미 검증한 과거 기록은 남긴다.
|
|
body = self.encode({**old, **data})
|
|
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
|
|
conn.execute('UPDATE snapshot SET body=?,revision=?,checked=?,attempted=?,saved=0 WHERE id=1', (body, self.revision(body), now, now))
|
|
return True
|
|
except Exception:
|
|
with closing(sqlite3.connect(self.path, timeout=10)) as conn, conn:
|
|
conn.execute('UPDATE snapshot SET attempted=?,saved=1 WHERE id=1', (now,))
|
|
return False
|
|
finally:
|
|
self.gate.release()
|