217 lines
8.4 KiB
Python
217 lines
8.4 KiB
Python
import json
|
||
import os
|
||
from datetime import datetime
|
||
from typing import Any, Dict, List, Tuple
|
||
|
||
|
||
def load_reservations(base_dir: str | None = None) -> Dict[int, Any]:
|
||
"""加载 reservations.json 并返回以 pos_seen 为键的映射字典。"""
|
||
if not base_dir:
|
||
try:
|
||
base_dir = os.path.abspath(
|
||
os.path.join(os.path.dirname(__file__), "..", "..")
|
||
)
|
||
except Exception:
|
||
base_dir = os.getcwd()
|
||
|
||
reservations_data: Dict[int, Any] = {}
|
||
reservations_paths = [
|
||
os.path.join(base_dir, "douyin", "core", "state", "reservations.json"),
|
||
os.path.join(base_dir, "douyin", "state", "reservations.json"),
|
||
os.path.join(os.getcwd(), "douyin", "core", "state", "reservations.json"),
|
||
]
|
||
for res_path in reservations_paths:
|
||
try:
|
||
if os.path.exists(res_path):
|
||
with open(res_path, "r", encoding="utf-8") as f:
|
||
raw = f.read()
|
||
parsed = json.loads(raw)
|
||
if isinstance(parsed, dict) and "queue" in parsed:
|
||
for item in parsed["queue"]:
|
||
pos = item.get("pos_seen", 0)
|
||
try:
|
||
if pos:
|
||
reservations_data[int(pos)] = item
|
||
except Exception:
|
||
# pos 可能不可转为 int,跳过
|
||
pass
|
||
break
|
||
except Exception:
|
||
# ignore malformed reservation files
|
||
pass
|
||
return reservations_data
|
||
|
||
|
||
def _format_timestamp(ts: Any) -> str:
|
||
try:
|
||
return datetime.fromtimestamp(float(ts)).strftime("%Y-%m-%d %H:%M:%S")
|
||
except Exception:
|
||
try:
|
||
return str(ts)
|
||
except Exception:
|
||
return "-"
|
||
|
||
|
||
def parse_entries(
|
||
parsed: Any,
|
||
show_title_raw: bool = False,
|
||
reservations_data: Dict[int, Any] | None = None,
|
||
) -> List[str]:
|
||
"""从解析后的 JSON 数据中生成 entries_pool(每项为多行文本)。
|
||
|
||
返回值:entries_pool(List[str]),每个字符串为一个条目的多行表示。
|
||
"""
|
||
if reservations_data is None:
|
||
reservations_data = {}
|
||
|
||
entries_pool: List[str] = []
|
||
|
||
if not parsed:
|
||
return entries_pool
|
||
|
||
# 如果是字典,按 key 排序(尽可能把纯数字当作数字排序)
|
||
if isinstance(parsed, dict):
|
||
try:
|
||
if "_meta" in parsed:
|
||
parsed = dict(parsed)
|
||
parsed.pop("_meta", None)
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
keys = sorted(
|
||
parsed.keys(), key=lambda x: int(x) if str(x).isdigit() else x
|
||
)
|
||
except Exception:
|
||
keys = list(parsed.keys())
|
||
|
||
for k in keys:
|
||
try:
|
||
v = parsed.get(k, {})
|
||
# prepare defaults
|
||
title = title_raw = "-"
|
||
has_fudai = ""
|
||
fudai_content = "-"
|
||
task_list = button_text = countdown_text = fudai_value = (
|
||
participants
|
||
) = copies = "-"
|
||
|
||
if isinstance(v, dict):
|
||
title = (v.get("title", "") or "").strip() or "-"
|
||
title_raw = (v.get("title_raw", "") or "").strip() or "-"
|
||
has_fudai = "✓" if v.get("has_fudai", False) else ""
|
||
fudai_content = (v.get("fudai_content", "") or "").strip() or "-"
|
||
|
||
fudai_detail = v.get("fudai_detail")
|
||
if isinstance(fudai_detail, dict):
|
||
task_list = (
|
||
str(fudai_detail.get("task_list") or "").strip() or "-"
|
||
)
|
||
button_text = (
|
||
str(fudai_detail.get("button_text") or "").strip() or "-"
|
||
)
|
||
fudai_time = (
|
||
str(fudai_detail.get("time_text") or "").strip() or "-"
|
||
)
|
||
fudai_value = (
|
||
f"{float(fudai_detail.get('prize_value_yuan') or 0):.2f}"
|
||
if fudai_detail.get("prize_value_yuan")
|
||
else "-"
|
||
)
|
||
participants = (
|
||
str(fudai_detail.get("participants") or 0)
|
||
if fudai_detail.get("participants")
|
||
else "-"
|
||
)
|
||
copies = (
|
||
str(fudai_detail.get("copies") or 0)
|
||
if fudai_detail.get("copies")
|
||
else "-"
|
||
)
|
||
mm = str(fudai_detail.get("countdown_mm") or "").strip()
|
||
ss = str(fudai_detail.get("countdown_ss") or "").strip()
|
||
if fudai_time and fudai_time != "-":
|
||
countdown_text = fudai_time
|
||
elif mm or ss:
|
||
if mm.isdigit() and len(mm) == 1:
|
||
mm = f"0{mm}"
|
||
if ss.isdigit() and len(ss) == 1:
|
||
ss = f"0{ss}"
|
||
if mm and ss:
|
||
countdown_text = f"{mm}:{ss}"
|
||
else:
|
||
countdown_text = mm or ss
|
||
elif (
|
||
fudai_detail
|
||
and isinstance(fudai_detail, (tuple, list))
|
||
and len(fudai_detail) >= 5
|
||
):
|
||
fudai_time = fudai_detail[1] or "-"
|
||
fudai_value = (
|
||
f"{fudai_detail[4] or 0:.2f}" if fudai_detail[4] else "-"
|
||
)
|
||
participants = (
|
||
str(fudai_detail[2] or 0) if fudai_detail[2] else "-"
|
||
)
|
||
copies = str(fudai_detail[3] or 0) if fudai_detail[3] else "-"
|
||
countdown_text = fudai_time or "-"
|
||
else:
|
||
fudai_time = "-"
|
||
|
||
try:
|
||
is_reserved = "✓" if int(k) in reservations_data else ""
|
||
except Exception:
|
||
is_reserved = ""
|
||
else:
|
||
# v is likely a list/tuple
|
||
try:
|
||
title = (v[0] or "").strip() or "-"
|
||
except Exception:
|
||
title = "-"
|
||
try:
|
||
title_raw = (v[1] or "").strip() or "-"
|
||
except Exception:
|
||
title_raw = "-"
|
||
is_reserved = ""
|
||
|
||
except Exception:
|
||
title = title_raw = "-"
|
||
has_fudai = ""
|
||
fudai_content = task_list = countdown_text = fudai_value = (
|
||
participants
|
||
) = copies = button_text = is_reserved = "-"
|
||
|
||
# timestamp
|
||
try:
|
||
ts = v.get("timestamp") if isinstance(v, dict) else None
|
||
if not ts and isinstance(v, dict):
|
||
fd = v.get("fudai_detail")
|
||
if isinstance(fd, dict):
|
||
ts = fd.get("timestamp")
|
||
updated_text = _format_timestamp(ts) if ts else "-"
|
||
except Exception:
|
||
updated_text = "-"
|
||
|
||
entry_lines: List[str] = []
|
||
entry_lines.append(f"[位置 {k}] {title}")
|
||
if show_title_raw:
|
||
entry_lines.append(f"原始标题: {title_raw}")
|
||
entry_lines.append(f"更新时间: {updated_text}")
|
||
entry_lines.append(f"已预约: {is_reserved}")
|
||
entry_lines.append(f"有福袋: {has_fudai}")
|
||
entry_lines.append(f"价值(元): {fudai_value}")
|
||
entry_lines.append(f"参与人数: {participants}")
|
||
entry_lines.append(f"份数: {copies}")
|
||
entry_lines.append(f"倒计时: {countdown_text}")
|
||
entry_lines.append(f"按钮: {button_text}")
|
||
entry_lines.append(f"任务列表: {task_list}")
|
||
entry_lines.append(f"福袋内容: {fudai_content}")
|
||
|
||
entries_pool.append("\n".join(entry_lines))
|
||
|
||
elif isinstance(parsed, (list, tuple)):
|
||
for i, v in enumerate(parsed):
|
||
entries_pool.append(str(v))
|
||
|
||
return entries_pool
|