332 lines
11 KiB
Python
332 lines
11 KiB
Python
"""
|
||
路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码
|
||
"""
|
||
import os
|
||
import sys
|
||
from typing import Optional
|
||
import json
|
||
|
||
def _detect_project_root() -> str:
|
||
"""返回运行根目录;源码运行是仓库根,PyInstaller 运行是 exe 所在目录。"""
|
||
if getattr(sys, "frozen", False):
|
||
return os.path.dirname(os.path.abspath(sys.executable))
|
||
# __file__ 位于 <project_root>/douyin/core/path_config.py,
|
||
# 所以项目根是当前文件向上两级目录。
|
||
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
|
||
# 项目根目录(所有路径的基准)
|
||
PROJECT_ROOT = _detect_project_root()
|
||
|
||
# 运行时路径与设备侧默认路径(支持环境变量覆盖,便于迁移)
|
||
DEFAULT_ANDROID_SCREENSHOT_PATH = "/sdcard/DCIM/screenshot.png"
|
||
DEFAULT_ANDROID_SCREENSHOT_ALT_PATH = "/sdcard/DCIM/screenshot1.png"
|
||
DEFAULT_ANDROID_WINDOW_DUMP_PATH = "/sdcard/window_dump.xml"
|
||
DEFAULT_DOUYIN_PACKAGES = (
|
||
"com.ss.android.ugc.aweme",
|
||
"com.ss.android.ugc.aweme.lite",
|
||
"com.zhiliaoapp.musically",
|
||
)
|
||
DEFAULT_ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
|
||
DEFAULT_WEB_GUI_HOST = "127.0.0.1"
|
||
DEFAULT_WEB_GUI_PORT = 8000
|
||
|
||
|
||
def get_project_root() -> str:
|
||
"""返回项目根目录(绝对路径)"""
|
||
return PROJECT_ROOT
|
||
|
||
|
||
def get_venv_python_path() -> str:
|
||
"""返回项目虚拟环境 Python 路径(Windows)。"""
|
||
return os.path.join(PROJECT_ROOT, ".venv", "Scripts", "python.exe")
|
||
|
||
|
||
def get_android_screenshot_path() -> str:
|
||
"""返回设备侧截图路径(可通过环境变量覆盖)。"""
|
||
return (
|
||
os.environ.get("ANDROID_SCREENSHOT_PATH", "").strip()
|
||
or DEFAULT_ANDROID_SCREENSHOT_PATH
|
||
)
|
||
|
||
|
||
def get_android_screenshot_alt_path() -> str:
|
||
"""返回设备侧备用截图路径(可通过环境变量覆盖)。"""
|
||
return (
|
||
os.environ.get("ANDROID_SCREENSHOT_ALT_PATH", "").strip()
|
||
or DEFAULT_ANDROID_SCREENSHOT_ALT_PATH
|
||
)
|
||
|
||
|
||
def get_android_window_dump_path() -> str:
|
||
"""返回设备侧 UI dump 路径(可通过环境变量覆盖)。"""
|
||
return (
|
||
os.environ.get("ANDROID_WINDOW_DUMP_PATH", "").strip()
|
||
or DEFAULT_ANDROID_WINDOW_DUMP_PATH
|
||
)
|
||
|
||
|
||
def get_douyin_packages() -> tuple[str, ...]:
|
||
"""返回抖音候选包名列表(支持环境变量覆盖,逗号分隔)。"""
|
||
raw = (os.environ.get("DOUYIN_PACKAGES", "") or "").strip()
|
||
if not raw:
|
||
return DEFAULT_DOUYIN_PACKAGES
|
||
items = tuple(x.strip() for x in raw.split(",") if x.strip())
|
||
return items or DEFAULT_DOUYIN_PACKAGES
|
||
|
||
|
||
def get_adb_keyboard_ime() -> str:
|
||
"""返回 ADBKeyboard IME(支持环境变量覆盖)。"""
|
||
return (os.environ.get("ADB_KEYBOARD_IME", "") or "").strip() or DEFAULT_ADB_KEYBOARD_IME
|
||
|
||
|
||
def _read_runtime_config() -> dict:
|
||
"""读取 config/config.json,失败时返回空字典。"""
|
||
try:
|
||
cfg_path = get_config_path()
|
||
if not os.path.exists(cfg_path):
|
||
return {}
|
||
with open(cfg_path, "r", encoding="utf-8") as f:
|
||
obj = json.load(f)
|
||
return obj if isinstance(obj, dict) else {}
|
||
except Exception:
|
||
return {}
|
||
|
||
|
||
def get_web_gui_host() -> str:
|
||
"""返回 Web GUI 监听 host(环境变量优先,其次 config.json,最后默认值)。"""
|
||
host = (os.environ.get("WEB_GUI_HOST") or "").strip()
|
||
if host:
|
||
return host
|
||
cfg = _read_runtime_config()
|
||
cfg_host = str(cfg.get("web_gui_host", "") or "").strip()
|
||
return cfg_host or DEFAULT_WEB_GUI_HOST
|
||
|
||
|
||
def get_web_gui_port() -> int:
|
||
"""返回 Web GUI 监听端口(环境变量优先,其次 config.json,最后默认值)。"""
|
||
env_raw = (os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "").strip()
|
||
if env_raw:
|
||
try:
|
||
port = int(env_raw)
|
||
if 1 <= port <= 65535:
|
||
return port
|
||
except Exception:
|
||
pass
|
||
|
||
cfg = _read_runtime_config()
|
||
cfg_raw = cfg.get("web_gui_port", DEFAULT_WEB_GUI_PORT)
|
||
try:
|
||
port = int(cfg_raw)
|
||
if 1 <= port <= 65535:
|
||
return port
|
||
except Exception:
|
||
pass
|
||
return DEFAULT_WEB_GUI_PORT
|
||
|
||
|
||
def get_config_path() -> str:
|
||
"""返回 config.json 的路径"""
|
||
return os.path.join(PROJECT_ROOT, "config", "config.json")
|
||
|
||
|
||
def get_logs_dir() -> str:
|
||
"""返回 logs 目录的路径"""
|
||
return os.path.join(PROJECT_ROOT, "logs")
|
||
|
||
|
||
def get_debug_log_path() -> str:
|
||
"""返回调试日志(debug.log)的路径"""
|
||
return os.path.join(get_logs_dir(), "debug.log")
|
||
|
||
def get_error_log_path() -> str:
|
||
"""返回错误日志(error.log)的路径"""
|
||
return os.path.join(get_logs_dir(), "error.log")
|
||
|
||
def get_log_file_path() -> str:
|
||
"""返回统一日志文件的路径"""
|
||
return os.path.join(PROJECT_ROOT, "logs", "unified.log")
|
||
|
||
|
||
def get_simple_log_path() -> str:
|
||
"""返回简洁日志文件的路径"""
|
||
return os.path.join(PROJECT_ROOT, "logs", "simple.log")
|
||
|
||
|
||
def get_detail_log_path() -> str:
|
||
"""返回详细日志文件的路径"""
|
||
return os.path.join(PROJECT_ROOT, "logs", "detail.log")
|
||
|
||
|
||
def get_actions_log_path() -> str:
|
||
"""返回行为日志文件 (actions.log) 的路径"""
|
||
return os.path.join(PROJECT_ROOT, "logs", "actions.log")
|
||
|
||
|
||
def get_pic_dir() -> str:
|
||
"""返回 pic 目录的路径(OCR截图、临时截图等)"""
|
||
return os.path.join(PROJECT_ROOT, "pic")
|
||
|
||
|
||
def get_screenshot_path() -> str:
|
||
"""返回 screenshot.png 的路径(当前屏幕截图)"""
|
||
return os.path.join(PROJECT_ROOT, "pic", "screenshot.png")
|
||
|
||
|
||
def get_state_dir() -> str:
|
||
"""返回 state 目录的路径(状态文件)"""
|
||
return os.path.join(PROJECT_ROOT, "state")
|
||
|
||
|
||
def get_reservations_path() -> str:
|
||
"""返回预约队列状态文件的路径(实际位置:douyin/core/state/reservations.json)。
|
||
|
||
该文件由 fudai_analyse 在 douyin/core/douyin_fudai.py 中写入,
|
||
供 WebGUI / 桌面 GUI 跨进程读取。
|
||
"""
|
||
return os.path.join(PROJECT_ROOT, "douyin", "core", "state", "reservations.json")
|
||
|
||
|
||
def get_high_value_rooms_path() -> str:
|
||
"""返回高价值房间状态文件的路径"""
|
||
return os.path.join(PROJECT_ROOT, "state", "high_value_rooms.json")
|
||
|
||
|
||
def get_assets_dir() -> str:
|
||
"""返回 assets 目录的路径(模板图片等)"""
|
||
return os.path.join(PROJECT_ROOT, "assets")
|
||
|
||
|
||
def get_like_template_path() -> str:
|
||
"""返回点赞图标模板的路径"""
|
||
return os.path.join(PROJECT_ROOT, "assets", "like.png")
|
||
|
||
|
||
def get_fav_template_path() -> str:
|
||
"""返回收藏图标模板的路径"""
|
||
return os.path.join(PROJECT_ROOT, "assets", "fav.png")
|
||
|
||
|
||
def get_desktop_template_path() -> str:
|
||
"""返回桌面图标模板的路径"""
|
||
return os.path.join(PROJECT_ROOT, "assets", "desktop.png")
|
||
|
||
|
||
def get_webui_dir() -> str:
|
||
"""返回 webui 目录的路径"""
|
||
return os.path.join(PROJECT_ROOT, "webui")
|
||
|
||
|
||
def get_pic_file_path(filename: str) -> str:
|
||
"""获取 pic 目录下指定文件的路径
|
||
|
||
Args:
|
||
filename: 文件名,可以是子目录/文件名,如 'diag_live_plaza.png' 或 'start/latest.png'
|
||
"""
|
||
return os.path.join(PROJECT_ROOT, "pic", filename)
|
||
|
||
|
||
def get_cut_pic_path(cut_pic_name: str) -> str:
|
||
"""获取裁剪后的图片路径(用于OCR)
|
||
|
||
Args:
|
||
cut_pic_name: 图片名称(不含扩展名),如 '直播广场'
|
||
"""
|
||
return os.path.join(PROJECT_ROOT, "pic", f"{cut_pic_name}.png")
|
||
|
||
|
||
def get_window_dump_path() -> str:
|
||
"""返回 window_dump.xml 的路径"""
|
||
return os.path.join(PROJECT_ROOT, "pic", "window_dump.xml")
|
||
|
||
|
||
def get_robot_verify_pic_path(save_subdir: bool = False) -> str:
|
||
"""返回机器人验证图片的路径
|
||
|
||
Args:
|
||
save_subdir: 是否在 pic/save 子目录中
|
||
"""
|
||
if save_subdir:
|
||
return os.path.join(PROJECT_ROOT, "pic", "save", "机器人验证.png")
|
||
return os.path.join(PROJECT_ROOT, "pic", "机器人验证.png")
|
||
|
||
|
||
def get_run_cli_path() -> str:
|
||
"""返回 run_cli.py 的路径(绝对路径)"""
|
||
return os.path.abspath(os.path.join(PROJECT_ROOT, "bin", "run_cli.py"))
|
||
|
||
|
||
def get_run_cli_command() -> list[str]:
|
||
"""返回启动 run_cli 的命令;源码模式用 Python 脚本,打包模式用同目录 exe。"""
|
||
if getattr(sys, "frozen", False):
|
||
exe_name = "run_cli.exe" if sys.platform.startswith("win") else "run_cli"
|
||
exe_path = os.path.join(PROJECT_ROOT, exe_name)
|
||
return [exe_path]
|
||
return [sys.executable, get_run_cli_path()]
|
||
|
||
|
||
def ensure_dir(path: str) -> None:
|
||
"""确保目录存在,不存在则创建"""
|
||
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
|
||
os.makedirs(dir_path, exist_ok=True)
|
||
|
||
|
||
def find_executable(cmd: str) -> Optional[str]:
|
||
"""尝试在系统环境中定位可执行命令的完整路径。
|
||
|
||
处理策略:
|
||
- 若 `cmd` 已是存在的路径则直接返回;
|
||
- 使用 `shutil.which` 尝试查找;
|
||
- 在 Windows 上回退到 `where`,在类 Unix 上回退到 `command -v` / `which`。
|
||
|
||
返回命令的绝对路径,找不到时返回 `None`。
|
||
"""
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import os
|
||
|
||
if not cmd:
|
||
return None
|
||
# 如果传入的是已有文件路径,直接返回绝对路径
|
||
if os.path.exists(cmd):
|
||
return os.path.abspath(cmd)
|
||
|
||
# 首选 shutil.which
|
||
try:
|
||
found = shutil.which(cmd)
|
||
if found:
|
||
return found
|
||
except Exception:
|
||
pass
|
||
|
||
# 平台回退检查
|
||
try:
|
||
if sys.platform.startswith("win"):
|
||
# 使用 where 查找(Windows)
|
||
# 注意:where 在未命中时会往 stderr 打印
|
||
# “INFO: Could not find files for the given pattern(s)”。
|
||
# 这里仅以 returncode/stdout 判断,不需要把该噪声透传到上层日志。
|
||
proc = subprocess.run(
|
||
["where", cmd],
|
||
capture_output=True,
|
||
text=True,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
if proc.returncode == 0 and proc.stdout:
|
||
first = proc.stdout.splitlines()[0].strip()
|
||
if first:
|
||
return first
|
||
else:
|
||
# 类 Unix:尝试 command -v 再 which
|
||
import shlex
|
||
proc = subprocess.run(["/bin/sh", "-c", f"command -v {shlex.quote(cmd)} || which {shlex.quote(cmd)}"], capture_output=True, text=True)
|
||
if proc.returncode == 0 and proc.stdout:
|
||
first = proc.stdout.splitlines()[0].strip()
|
||
if first:
|
||
return first
|
||
except Exception:
|
||
pass
|
||
|
||
return None
|