224 lines
7.1 KiB
Python
224 lines
7.1 KiB
Python
import os
|
|
import shutil
|
|
import logging
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import List, Dict, Optional, Any
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class BrowserProfileManager:
|
|
"""浏览器用户配置文件管理器."""
|
|
|
|
def __init__(self, settings: Dict[str, Any]):
|
|
"""
|
|
初始化浏览器配置文件管理器.
|
|
|
|
Args:
|
|
settings: 应用程序设置字典
|
|
"""
|
|
self.settings = settings
|
|
self.base_cache_dir = settings.get("profiles_dir", "")
|
|
|
|
# 确保基础缓存目录存在
|
|
if self.base_cache_dir and not os.path.exists(self.base_cache_dir):
|
|
os.makedirs(self.base_cache_dir, exist_ok=True)
|
|
|
|
def get_all_profiles(self) -> List[Dict[str, Any]]:
|
|
"""
|
|
获取所有浏览器配置文件.
|
|
|
|
Returns:
|
|
List[Dict]: 配置文件列表
|
|
"""
|
|
return self.settings.get("browser_profiles", [])
|
|
|
|
def get_profile_by_id(self, profile_id: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
通过ID获取浏览器配置文件.
|
|
|
|
Args:
|
|
profile_id: 配置文件ID
|
|
|
|
Returns:
|
|
Dict or None: 找到的配置文件或None
|
|
"""
|
|
profiles = self.get_all_profiles()
|
|
for profile in profiles:
|
|
if profile.get("profile_id") == profile_id:
|
|
return profile
|
|
return None
|
|
|
|
def create_profile(
|
|
self, profile_name: str, douyin_account: Optional[str] = None
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
创建新的浏览器配置文件.
|
|
|
|
Args:
|
|
profile_name: 配置文件名称
|
|
douyin_account: 关联的抖音账号(可选)
|
|
|
|
Returns:
|
|
Dict: 新创建的配置文件
|
|
"""
|
|
if not self.base_cache_dir:
|
|
raise ValueError("未设置浏览器缓存目录")
|
|
|
|
profile_id = str(uuid.uuid4())
|
|
profile_dir = os.path.join(self.base_cache_dir, f"Profile_{profile_id}")
|
|
|
|
# 创建配置文件目录
|
|
os.makedirs(profile_dir, exist_ok=True)
|
|
|
|
new_profile = {
|
|
"profile_id": profile_id,
|
|
"profile_name": profile_name,
|
|
"profile_dir": profile_dir,
|
|
"enabled": True,
|
|
"douyin_account": douyin_account,
|
|
"auto_reply_enabled": True,
|
|
"creation_time": datetime.now().isoformat(),
|
|
"last_used_time": None,
|
|
}
|
|
|
|
# 添加到配置文件列表
|
|
profiles = self.get_all_profiles()
|
|
profiles.append(new_profile)
|
|
self.settings["browser_profiles"] = profiles
|
|
|
|
# 保存设置
|
|
from douyin_imbot.config.settings import save_settings
|
|
|
|
save_settings(self.settings)
|
|
|
|
logger.info(f"已创建新的浏览器配置文件: {profile_name}")
|
|
return new_profile
|
|
|
|
def update_profile(self, profile_id: str, **kwargs) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
更新浏览器配置文件.
|
|
|
|
Args:
|
|
profile_id: 配置文件ID
|
|
**kwargs: 要更新的字段
|
|
|
|
Returns:
|
|
Dict or None: 更新后的配置文件或None
|
|
"""
|
|
profiles = self.get_all_profiles()
|
|
for i, profile in enumerate(profiles):
|
|
if profile.get("profile_id") == profile_id:
|
|
# 更新字段
|
|
for key, value in kwargs.items():
|
|
if key in profile and key != "profile_id": # 不允许更新profile_id
|
|
profile[key] = value
|
|
|
|
# 如果更新了名称,可能需要更新目录
|
|
if "profile_name" in kwargs:
|
|
logger.info(f"已更新配置文件名称: {kwargs['profile_name']}")
|
|
|
|
# 保存更新后的列表
|
|
self.settings["browser_profiles"] = profiles
|
|
from douyin_imbot.config.settings import save_settings
|
|
|
|
save_settings(self.settings)
|
|
|
|
return profile
|
|
|
|
logger.warning(f"未找到ID为{profile_id}的配置文件")
|
|
return None
|
|
|
|
def delete_profile(self, profile_id: str, delete_files: bool = False) -> bool:
|
|
"""
|
|
删除浏览器配置文件.
|
|
|
|
Args:
|
|
profile_id: 配置文件ID
|
|
delete_files: 是否同时删除配置文件目录
|
|
|
|
Returns:
|
|
bool: 删除成功返回True,否则返回False
|
|
"""
|
|
profiles = self.get_all_profiles()
|
|
for i, profile in enumerate(profiles):
|
|
if profile.get("profile_id") == profile_id:
|
|
# 如果需要,删除配置文件目录
|
|
if delete_files and "profile_dir" in profile:
|
|
profile_dir = profile["profile_dir"]
|
|
if os.path.exists(profile_dir):
|
|
try:
|
|
shutil.rmtree(profile_dir)
|
|
logger.info(f"已删除配置文件目录: {profile_dir}")
|
|
except Exception as e:
|
|
logger.error(f"删除配置文件目录时出错: {str(e)}")
|
|
|
|
# 从列表中删除
|
|
removed_profile = profiles.pop(i)
|
|
self.settings["browser_profiles"] = profiles
|
|
|
|
# 保存设置
|
|
from douyin_imbot.config.settings import save_settings
|
|
|
|
save_settings(self.settings)
|
|
|
|
logger.info(f"已删除配置文件: {removed_profile.get('profile_name')}")
|
|
return True
|
|
|
|
logger.warning(f"未找到ID为{profile_id}的配置文件")
|
|
return False
|
|
|
|
def set_base_cache_dir(self, directory: str) -> bool:
|
|
"""
|
|
设置浏览器缓存基础目录.
|
|
|
|
Args:
|
|
directory: 新的缓存目录路径
|
|
|
|
Returns:
|
|
bool: 设置成功返回True,否则返回False
|
|
"""
|
|
if not directory:
|
|
logger.error("缓存目录不能为空")
|
|
return False
|
|
|
|
# 确保目录存在
|
|
try:
|
|
os.makedirs(directory, exist_ok=True)
|
|
self.base_cache_dir = directory
|
|
self.settings["browser_cache_dir"] = directory
|
|
|
|
# 保存设置
|
|
from douyin_imbot.config.settings import save_settings
|
|
|
|
save_settings(self.settings)
|
|
|
|
logger.info(f"已设置浏览器缓存目录: {directory}")
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"设置缓存目录时出错: {str(e)}")
|
|
return False
|
|
|
|
def update_last_used_time(self, profile_id: str) -> None:
|
|
"""
|
|
更新配置文件的最后使用时间.
|
|
|
|
Args:
|
|
profile_id: 配置文件ID
|
|
"""
|
|
self.update_profile(profile_id, last_used_time=datetime.now().isoformat())
|
|
|
|
def clear_cache(self):
|
|
"""清除配置文件缓存"""
|
|
try:
|
|
# 清除所有缓存的配置文件信息
|
|
self._cached_profiles = None
|
|
# 强制下次请求重新从磁盘读取
|
|
self._last_refresh_time = 0
|
|
logger.debug("配置文件管理器缓存已清除")
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"清除配置文件管理器缓存失败: {str(e)}")
|
|
return False
|