refactor(gui): 抽 refresh_reservations 到 components/reservations_view (4913 → 4656)

This commit is contained in:
Your Name committed 2026-05-30 13:52:39 +08:00
1 parent 6bffcae2de
commit 5329561b3a
2 files changed
+278 -259

No files matched your search

+276
View File
@@ -0,0 +1,276 @@
"""预约队列 Tab 视图刷新逻辑。
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_reservations``,
负责读 ``state/reservations.json`` 并在 Tab 中以中文友好格式渲染预约明细。
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
"""
from __future__ import annotations
import json
import os
import tkinter as tk
from datetime import datetime
def refresh_reservations(text_widget: tk.Text) -> None:
try:
from douyin.core.path_config import get_reservations_path
path = get_reservations_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
path = path_config.get_reservations_path()
try:
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
text_widget.delete("1.0", "end")
updated_ts = (
float(data.get("updated_ts", 0.0) or 0.0)
if isinstance(data, dict)
else 0.0
)
room_pos = (
int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0
)
reason = (
str(data.get("reason", "") or "") if isinstance(data, dict) else ""
)
current_title = (
str(data.get("current_room_title", "") or "")
if isinstance(data, dict)
else ""
)
current_title_raw = (
str(data.get("current_room_title_raw", "") or "")
if isinstance(data, dict)
else ""
)
reservations = (
data.get("reservations", []) if isinstance(data, dict) else []
)
# 基本信息(中文,更详细)
lines = []
lines.append("=" * 60)
lines.append("【预约队列总览】")
lines.append("=" * 60)
if updated_ts > 0:
try:
updated_dt = datetime.fromtimestamp(updated_ts)
updated_str = updated_dt.strftime("%Y年%m月%d日 %H:%M:%S")
# 计算距离现在的时间
now_dt = datetime.now()
time_diff = now_dt - updated_dt
if time_diff.total_seconds() < 60:
time_ago = f"{int(time_diff.total_seconds())}秒前"
elif time_diff.total_seconds() < 3600:
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前"
elif time_diff.total_seconds() < 86400:
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前"
else:
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前"
lines.append(f"最后更新时间:{updated_str} ({time_ago})")
except Exception:
updated_str = str(updated_ts)
lines.append(f"最后更新时间:{updated_str}")
else:
lines.append("最后更新时间:暂无数据")
lines.append(
f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})"
)
lines.append(f"当前直播间名称(清洗后):{current_title or '未知'}")
lines.append(f"当前直播间名称(原始):{current_title_raw or '未知'}")
lines.append(f"预约队列总数:{len(reservations)} 条")
if reason:
reason_map = {
"record_reservation": "记录新预约",
"update_reservation": "更新预约信息",
"remove_expired": "移除过期预约",
"sort_reservations": "重新排序预约",
}
reason_text = reason_map.get(reason, reason)
lines.append(f"最近更新原因:{reason_text}")
lines.append("")
# 统计信息
if reservations:
now_ts = datetime.now().timestamp()
total_value = 0.0
valid_future_times = []
expired_count = 0
upcoming_count = 0
for item in reservations:
try:
val = float(item.get("prize_value_yuan") or 0.0)
total_value += val
except Exception:
pass
ft = float(item.get("future_ts") or 0.0)
if ft > 0:
valid_future_times.append(ft)
remain_sec = ft - now_ts
if remain_sec <= 0:
expired_count += 1
elif remain_sec <= 300: # 5分钟内
upcoming_count += 1
lines.append("【统计信息】")
lines.append(f"预约总价值:{total_value:.2f} 元")
if len(reservations) > 0:
avg_value = total_value / len(reservations)
lines.append(f"平均价值:{avg_value:.2f} 元")
if valid_future_times:
earliest_ts = min(valid_future_times)
latest_ts = max(valid_future_times)
try:
earliest_str = datetime.fromtimestamp(earliest_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
latest_str = datetime.fromtimestamp(latest_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
lines.append(f"最早开奖时间:{earliest_str}")
lines.append(f"最晚开奖时间:{latest_str}")
except Exception:
pass
if expired_count > 0:
lines.append(f"⚠️ 已过期预约:{expired_count} 条")
if upcoming_count > 0:
lines.append(f"⏰ 即将开奖(5分钟内):{upcoming_count} 条")
lines.append("")
lines.append("=" * 60)
lines.append("【预约明细列表】(按预计开奖时间从早到晚排序)")
lines.append("=" * 60)
lines.append("")
for idx, item in enumerate(reservations, start=1):
try:
val = float(item.get("prize_value_yuan") or 0.0)
except Exception:
val = 0.0
content = str(item.get("content") or "")
ft = float(item.get("future_ts") or 0.0)
ft_str = str(item.get("future_str") or "")
pos_seen = int(item.get("pos_seen") or 0)
room_title = str(item.get("room_title") or "")
room_title_raw = str(item.get("room_title_raw") or "")
created_ts = float(item.get("created_ts") or 0.0)
# 计算剩余时间(更详细)
now_ts = datetime.now().timestamp()
remain_sec = ft - now_ts if ft > 0 else 0
if ft <= 0:
remain_str = "❌ 开奖时间无效"
status_icon = "❌"
elif remain_sec <= 0:
remain_str = "⏰ 已到开奖时间"
status_icon = "⏰"
elif remain_sec <= 60:
remain_str = f"🔥 即将开奖({int(remain_sec)}秒后)"
status_icon = "🔥"
elif remain_sec <= 300:
remain_str = f"⏰ 即将开奖({int(remain_sec // 60)}分{int(remain_sec % 60)}秒后)"
status_icon = "⏰"
elif remain_sec <= 3600:
remain_str = f"⏳ {int(remain_sec // 60)}分{int(remain_sec % 60)}秒后开奖"
status_icon = "⏳"
elif remain_sec <= 86400:
hours = int(remain_sec // 3600)
minutes = int((remain_sec % 3600) // 60)
remain_str = f"⏳ {hours}小时{minutes}分钟后开奖"
status_icon = "⏳"
else:
days = int(remain_sec // 86400)
hours = int((remain_sec % 86400) // 3600)
remain_str = f"📅 {days}天{hours}小时后开奖"
status_icon = "📅"
# 记录时间(更详细)
if created_ts > 0:
try:
created_dt = datetime.fromtimestamp(created_ts)
created_str = created_dt.strftime(
"%Y年%m月%d日 %H:%M:%S"
)
# 计算距离现在的时间
time_diff = datetime.now() - created_dt
if time_diff.total_seconds() < 3600:
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前记录"
elif time_diff.total_seconds() < 86400:
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前记录"
else:
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前记录"
created_str_full = f"{created_str} ({time_ago})"
except Exception:
created_str_full = str(created_ts)
else:
created_str_full = "未知"
# 格式化显示
lines.append(
"┌─ 预约 #"
+ str(idx)
+ " ─────────────────────────────────────────────"
)
lines.append(f"│ 状态:{status_icon} {remain_str}")
lines.append("│")
lines.append(f"│ 💰 奖品价值:{val:.2f} 元")
lines.append(f"│ 📦 奖品内容:{content or '(无描述)'}")
lines.append("│")
lines.append(f"│ ⏰ 预计开奖时间:{ft_str or '未知'}")
if ft > 0:
try:
ft_dt = datetime.fromtimestamp(ft)
ft_str_detailed = ft_dt.strftime(
"%Y年%m月%d日 %H:%M:%S"
)
if ft_str_detailed != ft_str:
lines.append(f"│ 详细时间:{ft_str_detailed}")
except Exception:
pass
lines.append("│")
lines.append(
f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})"
)
lines.append(
f"│ 🏠 直播间名称(清洗后):{room_title or '未知'}"
)
lines.append(
f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}"
)
lines.append("│")
lines.append(f"│ 📝 记录时间:{created_str_full}")
lines.append(f"└{'─' * 58}")
lines.append("")
else:
lines.append("【预约明细列表】")
lines.append("")
lines.append("暂无预约记录。")
lines.append("")
lines.append(
"提示:当检测到高价值福袋时,系统会自动将其加入预约队列。"
)
text_widget.insert("1.0", "\n".join(lines))
else:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", "暂无预约队列数据")
except Exception as e:
text_widget.delete("1.0", "end")
text_widget.insert("1.0", f"读取预约队列失败:{e}")
+2 -259
View File
@@ -47,6 +47,7 @@ from douyin.core.path_config import get_logs_dir
from gui.components.mapping_table import create_mapping_tab
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
# 导入日志颜色配置模块
try:
@@ -3965,265 +3966,7 @@ def main():
pass
def refresh_reservations():
try:
from douyin.core.path_config import get_reservations_path
path = get_reservations_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
path = path_config.get_reservations_path()
try:
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
reservation_text.delete("1.0", "end")
updated_ts = (
float(data.get("updated_ts", 0.0) or 0.0)
if isinstance(data, dict)
else 0.0
)
room_pos = (
int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0
)
reason = (
str(data.get("reason", "") or "") if isinstance(data, dict) else ""
)
current_title = (
str(data.get("current_room_title", "") or "")
if isinstance(data, dict)
else ""
)
current_title_raw = (
str(data.get("current_room_title_raw", "") or "")
if isinstance(data, dict)
else ""
)
reservations = (
data.get("reservations", []) if isinstance(data, dict) else []
)
# 基本信息(中文,更详细)
lines = []
lines.append("=" * 60)
lines.append("【预约队列总览】")
lines.append("=" * 60)
if updated_ts > 0:
try:
updated_dt = datetime.fromtimestamp(updated_ts)
updated_str = updated_dt.strftime("%Y年%m月%d日 %H:%M:%S")
# 计算距离现在的时间
now_dt = datetime.now()
time_diff = now_dt - updated_dt
if time_diff.total_seconds() < 60:
time_ago = f"{int(time_diff.total_seconds())}秒前"
elif time_diff.total_seconds() < 3600:
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前"
elif time_diff.total_seconds() < 86400:
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前"
else:
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前"
lines.append(f"最后更新时间:{updated_str} ({time_ago})")
except Exception:
updated_str = str(updated_ts)
lines.append(f"最后更新时间:{updated_str}")
else:
lines.append("最后更新时间:暂无数据")
lines.append(
f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})"
)
lines.append(f"当前直播间名称(清洗后):{current_title or '未知'}")
lines.append(f"当前直播间名称(原始):{current_title_raw or '未知'}")
lines.append(f"预约队列总数:{len(reservations)} 条")
if reason:
reason_map = {
"record_reservation": "记录新预约",
"update_reservation": "更新预约信息",
"remove_expired": "移除过期预约",
"sort_reservations": "重新排序预约",
}
reason_text = reason_map.get(reason, reason)
lines.append(f"最近更新原因:{reason_text}")
lines.append("")
# 统计信息
if reservations:
now_ts = datetime.now().timestamp()
total_value = 0.0
valid_future_times = []
expired_count = 0
upcoming_count = 0
for item in reservations:
try:
val = float(item.get("prize_value_yuan") or 0.0)
total_value += val
except Exception:
pass
ft = float(item.get("future_ts") or 0.0)
if ft > 0:
valid_future_times.append(ft)
remain_sec = ft - now_ts
if remain_sec <= 0:
expired_count += 1
elif remain_sec <= 300: # 5分钟内
upcoming_count += 1
lines.append("【统计信息】")
lines.append(f"预约总价值:{total_value:.2f} 元")
if len(reservations) > 0:
avg_value = total_value / len(reservations)
lines.append(f"平均价值:{avg_value:.2f} 元")
if valid_future_times:
earliest_ts = min(valid_future_times)
latest_ts = max(valid_future_times)
try:
earliest_str = datetime.fromtimestamp(earliest_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
latest_str = datetime.fromtimestamp(latest_ts).strftime(
"%Y-%m-%d %H:%M:%S"
)
lines.append(f"最早开奖时间:{earliest_str}")
lines.append(f"最晚开奖时间:{latest_str}")
except Exception:
pass
if expired_count > 0:
lines.append(f"⚠️ 已过期预约:{expired_count} 条")
if upcoming_count > 0:
lines.append(f"⏰ 即将开奖(5分钟内):{upcoming_count} 条")
lines.append("")
lines.append("=" * 60)
lines.append("【预约明细列表】(按预计开奖时间从早到晚排序)")
lines.append("=" * 60)
lines.append("")
for idx, item in enumerate(reservations, start=1):
try:
val = float(item.get("prize_value_yuan") or 0.0)
except Exception:
val = 0.0
content = str(item.get("content") or "")
ft = float(item.get("future_ts") or 0.0)
ft_str = str(item.get("future_str") or "")
pos_seen = int(item.get("pos_seen") or 0)
room_title = str(item.get("room_title") or "")
room_title_raw = str(item.get("room_title_raw") or "")
created_ts = float(item.get("created_ts") or 0.0)
# 计算剩余时间(更详细)
now_ts = datetime.now().timestamp()
remain_sec = ft - now_ts if ft > 0 else 0
if ft <= 0:
remain_str = "❌ 开奖时间无效"
status_icon = "❌"
elif remain_sec <= 0:
remain_str = "⏰ 已到开奖时间"
status_icon = "⏰"
elif remain_sec <= 60:
remain_str = f"🔥 即将开奖({int(remain_sec)}秒后)"
status_icon = "🔥"
elif remain_sec <= 300:
remain_str = f"⏰ 即将开奖({int(remain_sec // 60)}分{int(remain_sec % 60)}秒后)"
status_icon = "⏰"
elif remain_sec <= 3600:
remain_str = f"⏳ {int(remain_sec // 60)}分{int(remain_sec % 60)}秒后开奖"
status_icon = "⏳"
elif remain_sec <= 86400:
hours = int(remain_sec // 3600)
minutes = int((remain_sec % 3600) // 60)
remain_str = f"⏳ {hours}小时{minutes}分钟后开奖"
status_icon = "⏳"
else:
days = int(remain_sec // 86400)
hours = int((remain_sec % 86400) // 3600)
remain_str = f"📅 {days}天{hours}小时后开奖"
status_icon = "📅"
# 记录时间(更详细)
if created_ts > 0:
try:
created_dt = datetime.fromtimestamp(created_ts)
created_str = created_dt.strftime(
"%Y年%m月%d日 %H:%M:%S"
)
# 计算距离现在的时间
time_diff = datetime.now() - created_dt
if time_diff.total_seconds() < 3600:
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前记录"
elif time_diff.total_seconds() < 86400:
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前记录"
else:
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前记录"
created_str_full = f"{created_str} ({time_ago})"
except Exception:
created_str_full = str(created_ts)
else:
created_str_full = "未知"
# 格式化显示
lines.append(
"┌─ 预约 #"
+ str(idx)
+ " ─────────────────────────────────────────────"
)
lines.append(f"│ 状态:{status_icon} {remain_str}")
lines.append("│")
lines.append(f"│ 💰 奖品价值:{val:.2f} 元")
lines.append(f"│ 📦 奖品内容:{content or '(无描述)'}")
lines.append("│")
lines.append(f"│ ⏰ 预计开奖时间:{ft_str or '未知'}")
if ft > 0:
try:
ft_dt = datetime.fromtimestamp(ft)
ft_str_detailed = ft_dt.strftime(
"%Y年%m月%d日 %H:%M:%S"
)
if ft_str_detailed != ft_str:
lines.append(f"│ 详细时间:{ft_str_detailed}")
except Exception:
pass
lines.append("│")
lines.append(
f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})"
)
lines.append(
f"│ 🏠 直播间名称(清洗后):{room_title or '未知'}"
)
lines.append(
f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}"
)
lines.append("│")
lines.append(f"│ 📝 记录时间:{created_str_full}")
lines.append(f"└{'─' * 58}")
lines.append("")
else:
lines.append("【预约明细列表】")
lines.append("")
lines.append("暂无预约记录。")
lines.append("")
lines.append(
"提示:当检测到高价值福袋时,系统会自动将其加入预约队列。"
)
reservation_text.insert("1.0", "\n".join(lines))
else:
reservation_text.delete("1.0", "end")
reservation_text.insert("1.0", "暂无预约队列数据")
except Exception as e:
reservation_text.delete("1.0", "end")
reservation_text.insert("1.0", f"读取预约队列失败:{e}")
_refresh_reservations_impl(reservation_text)
ttk.Button(reservation_top, text="刷新", command=refresh_reservations).pack(
side=LEFT