xhs_factory/services/autostart.py
zhoujie b635108b89 refactor: split monolithic main.py into services/ + ui/ modules (improve-maintainability)
- main.py: 4360 → 146 lines (96.6% reduction), entry layer only
- services/: rate_limiter, autostart, persona, connection, profile,
  hotspot, content, engagement, scheduler, queue_ops (10 business modules)
- ui/app.py: all Gradio UI code extracted into build_app(cfg, analytics)
- Fix: with gr.Blocks() indented inside build_app function
- Fix: cfg.all property (not get_all method)
- Fix: STATUS_LABELS, get_persona_keywords, fetch_proactive_notes imports
- Fix: queue_ops module-level set_publish_callback moved into configure()
- Fix: pub_queue.format_*() wrapped as queue_format_table/calendar helpers
- All 14 files syntax-verified, build_app() runtime-verified
- 58/58 tasks complete"
2026-02-24 22:50:56 +08:00

122 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
services/autostart.py
Windows 开机自启管理
"""
import os
import platform
import logging
logger = logging.getLogger("autobot")
_APP_NAME = "XHS_AI_AutoBot"
_STARTUP_REG_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
def _get_startup_script_path() -> str:
"""获取启动脚本路径(.vbs 静默启动,不弹黑窗)"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "_autostart.vbs")
def _get_startup_bat_path() -> str:
"""获取启动 bat 路径"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "_autostart.bat")
def _create_startup_scripts():
"""创建静默启动脚本bat + vbs"""
app_dir = os.path.dirname(os.path.abspath(os.path.join(__file__, "..")))
# __file__ is services/autostart.py, so app_dir should be parent
app_dir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
venv_python = os.path.join(app_dir, ".venv", "Scripts", "pythonw.exe")
# 如果没有 pythonw退回 python.exe
if not os.path.exists(venv_python):
venv_python = os.path.join(app_dir, ".venv", "Scripts", "python.exe")
main_script = os.path.join(app_dir, "main.py")
# 创建 bat
bat_path = _get_startup_bat_path()
bat_content = f"""@echo off
cd /d "{app_dir}"
"{venv_python}" "{main_script}"
"""
with open(bat_path, "w", encoding="utf-8") as f:
f.write(bat_content)
# 创建 vbs静默运行 bat不弹出命令行窗口
vbs_path = _get_startup_script_path()
vbs_content = f"""Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "{bat_path}" & chr(34), 0
Set WshShell = Nothing
"""
with open(vbs_path, "w", encoding="utf-8") as f:
f.write(vbs_content)
return vbs_path
def is_autostart_enabled() -> bool:
"""检查是否已设置开机自启"""
if platform.system() != "Windows":
return False
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, _STARTUP_REG_KEY, 0, winreg.KEY_READ)
try:
val, _ = winreg.QueryValueEx(key, _APP_NAME)
winreg.CloseKey(key)
return bool(val)
except FileNotFoundError:
winreg.CloseKey(key)
return False
except Exception:
return False
def enable_autostart() -> str:
"""启用 Windows 开机自启"""
if platform.system() != "Windows":
return "❌ 此功能仅支持 Windows 系统"
try:
import winreg
vbs_path = _create_startup_scripts()
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, _STARTUP_REG_KEY, 0, winreg.KEY_SET_VALUE)
# 用 wscript 运行 vbs 以实现静默启动
winreg.SetValueEx(key, _APP_NAME, 0, winreg.REG_SZ, f'wscript.exe "{vbs_path}"')
winreg.CloseKey(key)
logger.info(f"开机自启已启用: {vbs_path}")
return "✅ 开机自启已启用\n下次开机时将自动后台运行本程序"
except Exception as e:
logger.error(f"设置开机自启失败: {e}")
return f"❌ 设置失败: {e}"
def disable_autostart() -> str:
"""禁用 Windows 开机自启"""
if platform.system() != "Windows":
return "❌ 此功能仅支持 Windows 系统"
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, _STARTUP_REG_KEY, 0, winreg.KEY_SET_VALUE)
try:
winreg.DeleteValue(key, _APP_NAME)
except FileNotFoundError:
pass
winreg.CloseKey(key)
# 清理启动脚本
for f in [_get_startup_script_path(), _get_startup_bat_path()]:
if os.path.exists(f):
os.remove(f)
logger.info("开机自启已禁用")
return "✅ 开机自启已禁用"
except Exception as e:
logger.error(f"禁用开机自启失败: {e}")
return f"❌ 禁用失败: {e}"
def toggle_autostart(enabled: bool) -> str:
"""切换开机自启状态(供 UI 调用)"""
if enabled:
return enable_autostart()
else:
return disable_autostart()