96 lines
2.1 KiB
Python
96 lines
2.1 KiB
Python
"""辅助工具函数"""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
from typing import List
|
|
from loguru import logger
|
|
|
|
from douyu.config import Account
|
|
|
|
|
|
def load_accounts(config_path: str = "config.yaml") -> List[Account]:
|
|
"""加载账号列表"""
|
|
from douyu.config import Config
|
|
|
|
config = Config(config_path)
|
|
accounts = config.get_accounts()
|
|
|
|
logger.info(f"加载了 {len(accounts)} 个账号")
|
|
return accounts
|
|
|
|
|
|
def save_cookie(username: str, cookie: str, cookie_dir: str = "data/cookies") -> str:
|
|
"""
|
|
保存Cookie到文件
|
|
|
|
Args:
|
|
username: 用户名
|
|
cookie: Cookie字符串
|
|
cookie_dir: Cookie存储目录
|
|
|
|
Returns:
|
|
文件路径
|
|
"""
|
|
import time
|
|
|
|
cookie_path = Path(cookie_dir)
|
|
cookie_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
filepath = cookie_path / f"{username}.json"
|
|
|
|
data = {
|
|
'username': username,
|
|
'cookie': cookie,
|
|
'timestamp': int(time.time()),
|
|
}
|
|
|
|
with open(filepath, 'w', encoding='utf-8') as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
|
|
logger.info(f"Cookie已保存: {filepath}")
|
|
return str(filepath)
|
|
|
|
|
|
def load_cookie(username: str, cookie_dir: str = "data/cookies") -> str:
|
|
"""
|
|
从文件加载Cookie
|
|
|
|
Args:
|
|
username: 用户名
|
|
cookie_dir: Cookie存储目录
|
|
|
|
Returns:
|
|
Cookie字符串,不存在返回空字符串
|
|
"""
|
|
filepath = Path(cookie_dir) / f"{username}.json"
|
|
|
|
if not filepath.exists():
|
|
return ""
|
|
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
data = json.load(f)
|
|
return data.get('cookie', '')
|
|
except Exception as e:
|
|
logger.error(f"加载Cookie失败: {e}")
|
|
return ""
|
|
|
|
|
|
def format_cookie_for_browser(cookie_str: str) -> dict:
|
|
"""
|
|
将Cookie字符串转换为浏览器格式
|
|
|
|
Args:
|
|
cookie_str: Cookie字符串
|
|
|
|
Returns:
|
|
Cookie字典
|
|
"""
|
|
cookies = {}
|
|
for item in cookie_str.split(';'):
|
|
item = item.strip()
|
|
if '=' in item:
|
|
key, value = item.split('=', 1)
|
|
cookies[key.strip()] = value.strip()
|
|
return cookies
|