# =========================================== # 班级操行分管理系统 - 后端服务 # # 开发者: Canglan # 联系方式: admin@sea-studio.top # 版权归属: Sea Network Technology Studio # 许可证: MIT License # # 版权所有 © Sea Network Technology Studio # =========================================== """节假日服务:优先使用国内接口获取法定节假日与调休补班(缓存 + 失败降级)""" import json import ssl import time import asyncio import urllib.error import urllib.request from datetime import date from typing import Dict, Any from utils.logger import get_logger logger = get_logger(__name__) # 国内节假日接口(apihubs.cn,国内节点、无 Cloudflare) HOLIDAY_API_DOMESTIC = 'https://api.apihubs.cn/holiday/get?year={year}&size=400' # 备用接口(节假曰 API),仅在主接口不可用时使用 HOLIDAY_API_FALLBACK = 'https://api.jiejiariapi.com/v1/holidays/{year}' CACHE_TTL = 12 * 3600 FAIL_CACHE_TTL = 600 REQUEST_TIMEOUT = 6 _cache: Dict[int, Dict[str, Any]] = {} def _urlopen_json(url: str) -> Any: """请求 JSON(证书校验失败时回退为不校验重试一次)""" request = urllib.request.Request( url, headers={'User-Agent': 'ClassManager/4.5 (HolidayFetcher)'} ) try: with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT) as response: return json.loads(response.read().decode('utf-8')) except (ssl.SSLError, urllib.error.URLError) as e: logger.warning(f"节假日接口证书校验失败,回退重试: {e}") context = ssl._create_unverified_context() with urllib.request.urlopen(request, timeout=REQUEST_TIMEOUT, context=context) as response: return json.loads(response.read().decode('utf-8')) def _fetch_domestic(year: int) -> Dict[str, Any]: """国内接口(apihubs.cn):按 workday/weekend 标志解析放假与调休补班""" payload = _urlopen_json(HOLIDAY_API_DOMESTIC.format(year=year)) items = (payload.get('data') or {}).get('list') or [] if not items: raise ValueError("国内接口未返回数据") holidays: Dict[str, str] = {} workdays: Dict[str, str] = {} for item in items: try: date_int = int(item.get('date') or 0) except (TypeError, ValueError): continue if date_int < 20000101: continue s = str(date_int) day = f'{s[0:4]}-{s[4:6]}-{s[6:8]}' # workday: 1=上班, 2=休息;weekend: 1=周六/日, 2=工作日 if item.get('workday') == 2 and item.get('weekend') == 2: holidays[day] = '法定节假日' elif item.get('workday') == 1 and item.get('weekend') == 1: workdays[day] = '调休补班' if not holidays: raise ValueError("国内接口未解析到节假日数据") return {'holidays': holidays, 'workdays': workdays, 'api_ok': True} def _fetch_fallback(year: int) -> Dict[str, Any]: """备用接口(节假曰 API):放假 + 调休补班""" payload = _urlopen_json(HOLIDAY_API_FALLBACK.format(year=year)) if not isinstance(payload, dict) or not payload: raise ValueError("备用接口返回数据为空") holidays: Dict[str, str] = {} workdays: Dict[str, str] = {} for key, info in payload.items(): if not isinstance(info, dict): continue day = str(info.get('date') or key)[:10] name = info.get('name') or ('节假日' if info.get('isOffDay') else '调休补班') if info.get('isOffDay'): holidays[day] = name else: workdays[day] = name if not holidays: raise ValueError("备用接口未返回节假日数据") return {'holidays': holidays, 'workdays': workdays, 'api_ok': True} def _fetch_year_sync(year: int) -> Dict[str, Any]: """同步获取某年节假日数据:国内接口优先,失败后尝试备用接口""" try: return _fetch_domestic(year) except Exception as e: logger.warning(f"国内节假日接口获取失败({year}),尝试备用接口: {e}") try: return _fetch_fallback(year) except Exception as e: logger.warning(f"备用节假日接口获取失败({year}): {e}") return {'holidays': {}, 'workdays': {}, 'api_ok': False} async def get_year_data(year: int) -> Dict[str, Any]: """获取某年的节假日/调休数据(内存缓存,接口失败自动降级)""" now = time.time() cached = _cache.get(year) if cached: ttl = CACHE_TTL if cached.get('api_ok') else FAIL_CACHE_TTL if now - cached['fetched_at'] < ttl: return cached try: loop = asyncio.get_running_loop() data = await loop.run_in_executor(None, _fetch_year_sync, year) data['fetched_at'] = now _cache[year] = data if data['api_ok']: logger.info( f"节假日数据获取成功: {year}年,放假{len(data['holidays'])}天,调休补班{len(data['workdays'])}天" ) else: logger.warning(f"节假日数据获取失败: {year}年(接口均不可用)") return data except Exception as e: logger.warning(f"节假日数据获取异常({year}): {e}") failed = {'holidays': {}, 'workdays': {}, 'api_ok': False, 'fetched_at': now} _cache[year] = failed return failed async def get_range_data(start: date, end: date) -> Dict[str, Any]: """获取日期范围内的节假日/调休数据""" holidays: Dict[str, str] = {} workdays: Dict[str, str] = {} api_ok = True for year in range(start.year, end.year + 1): data = await get_year_data(year) holidays.update(data['holidays']) workdays.update(data['workdays']) api_ok = api_ok and data['api_ok'] start_iso = start.isoformat() end_iso = end.isoformat() return { 'holidays': {d: n for d, n in holidays.items() if start_iso <= d <= end_iso}, 'workdays': {d: n for d, n in workdays.items() if start_iso <= d <= end_iso}, 'api_ok': api_ok }