Files
douyin_guaji-main/douyin/reservation/douyin_reservation.py
T
Your Name c67f22f76f feat: Refactor and reorganize project structure with new modules and files
- Deleted obsolete files including test scripts and configuration files to streamline the project.
- Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components.
- Updated import paths to reflect the new module structure, enhancing code organization and maintainability.
- Added configuration files and documentation to support the new structure and improve user guidance.
2025-12-28 14:16:40 +08:00

124 lines
3.9 KiB
Python

from __future__ import annotations
import json
import os
import time
from datetime import datetime
def _write_json_atomic(path: str, data: object, *, indent: int = 2) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=indent)
f.write("\n")
os.replace(tmp, path)
def write_reservations_state(
*,
state_path: str,
reservations: list[dict],
room_pos: int,
current_room_title: str,
current_room_title_raw: str,
reason: str = "",
) -> None:
"""寫入預約隊列狀態(跨進程可讀)。"""
try:
items: list[dict] = []
for r in reservations or []:
try:
ft = float(r.get("future_ts") or 0)
except Exception:
ft = 0.0
try:
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else ""
except Exception:
ft_str = ""
items.append(
{
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
"content": str(r.get("content") or ""),
"future_ts": ft,
"future_str": ft_str,
"pos_seen": int(r.get("pos_seen") or 0),
"room_title": str(r.get("room_title") or ""),
"room_title_raw": str(r.get("room_title_raw") or ""),
"task_count": int(r.get("task_count") or 2),
"time_text": str(r.get("time_text") or ""),
"participants": int(r.get("participants") or 0),
"copies": int(r.get("copies") or 0),
}
)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"room_pos": int(room_pos),
"current_room_title": str(current_room_title or ""),
"current_room_title_raw": str(current_room_title_raw or ""),
"reservations": items,
}
_write_json_atomic(state_path, data, indent=2)
except Exception as e:
try:
print(f"[预约队列] 写入状态文件失败: {type(e).__name__}: {e}")
except Exception:
pass
def load_high_value_rooms_map(path: str) -> dict[str, dict]:
"""讀取高價值直播間映射(跨運行持久化)。"""
try:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
# 兼容兩種格式:{"rooms": [...]} 或 直接是 [...]
rooms = None
if isinstance(data, dict):
rooms = data.get("rooms")
elif isinstance(data, list):
rooms = data
out: dict[str, dict] = {}
if isinstance(rooms, list):
for it in rooms:
if not isinstance(it, dict):
continue
key = str(it.get("room_title") or "").strip()
if not key:
continue
out[key] = dict(it)
return out
except Exception:
return {}
def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "") -> None:
"""寫入高價值直播間映射(跨運行持久化)。"""
try:
rooms: list[dict] = []
for k, v in (rooms_map or {}).items():
if not k:
continue
item = dict(v or {})
item["room_title"] = str(k)
rooms.append(item)
rooms.sort(key=lambda x: float(x.get("last_seen_ts") or 0.0), reverse=True)
data = {
"updated_ts": time.time(),
"reason": str(reason or ""),
"total": int(len(rooms)),
"rooms": rooms,
}
_write_json_atomic(path, data, indent=2)
except Exception:
pass