初版:教务抢课系统 jwxt(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,542 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Session管理工具类
|
||||
负责检测、刷新和管理教务系统Session
|
||||
|
||||
账号分离设计:
|
||||
- 网站账号:存储在数据库 (User模型)
|
||||
- 教务系统账号:存储在 accounts.json
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import base64
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from app.time_utils import now as bj_now
|
||||
|
||||
import requests
|
||||
from Crypto.PublicKey import RSA
|
||||
from Crypto.Cipher import PKCS1_v1_5
|
||||
|
||||
from app.jwxt_login import JWXTLogin
|
||||
from app.account_manager import AccountManager
|
||||
|
||||
from app.settings import SESSION_DIR
|
||||
from app.url_manager import get_base_url
|
||||
SESSION_DIR.mkdir(exist_ok=True)
|
||||
|
||||
class SessionManager:
|
||||
"""Session管理器"""
|
||||
|
||||
@staticmethod
|
||||
def get_session_file(username):
|
||||
"""获取session文件路径"""
|
||||
from app.school_manager import session_key
|
||||
return SESSION_DIR / f"{session_key(username)}.json"
|
||||
|
||||
@staticmethod
|
||||
def _save_session_atomic(username, data, login_base_url=None):
|
||||
"""
|
||||
原子保存 session 文件,并处理多线路错配:
|
||||
登录耗时数秒(OCR 重试),期间全局线路可能已切换、或用户固定了其他
|
||||
线路——此时这份 cookie 不能覆盖生效文件(会造成 cookie 与请求线路
|
||||
错配),改写入对应线路的预热文件,由 multi_line 统一调度。
|
||||
|
||||
本方法可能在无学校上下文的后台线程被调用,先按账号绑定学校,
|
||||
否则 session 文件命名会落到默认学校(多学校场景错写文件)。
|
||||
"""
|
||||
data_json = json.dumps(data, ensure_ascii=False, indent=2)
|
||||
from app.url_manager import push_school, pop_school
|
||||
from app.school_manager import school_for_username
|
||||
acc_school = school_for_username(username)
|
||||
push_school(acc_school)
|
||||
try:
|
||||
target = SessionManager.get_session_file(username)
|
||||
try:
|
||||
from app import multi_line as ml
|
||||
if ml.is_enabled(acc_school) and login_base_url:
|
||||
login_tag = ml.line_tag(login_base_url)
|
||||
pref = ml.get_user_preference(username, acc_school)
|
||||
if pref in ('auto', '', None):
|
||||
from app.url_manager import get_global_base_url
|
||||
serving_tag = ml.line_tag(get_global_base_url(acc_school))
|
||||
else:
|
||||
serving_tag = pref
|
||||
if login_tag != serving_tag:
|
||||
ml._atomic_write_json(ml._line_session_file(username, login_tag), data)
|
||||
logging.getLogger(__name__).info(
|
||||
f"[session_manager] 登录线路({login_tag})与生效线路({serving_tag})不一致,"
|
||||
f"cookie 已写入预热文件,不覆盖生效 session"
|
||||
)
|
||||
return
|
||||
except ImportError:
|
||||
pass
|
||||
# 原子写入生效文件(避免抢课线程读到半截 JSON)
|
||||
try:
|
||||
from app import multi_line as ml
|
||||
ml._atomic_write_json(target, data)
|
||||
except Exception:
|
||||
target.write_text(data_json, encoding="utf-8")
|
||||
finally:
|
||||
pop_school()
|
||||
|
||||
@staticmethod
|
||||
def is_session_valid(username):
|
||||
"""
|
||||
检查session是否有效
|
||||
返回: (is_valid, error_msg)
|
||||
"""
|
||||
import requests
|
||||
|
||||
session_file = SessionManager.get_session_file(username)
|
||||
if not session_file.exists():
|
||||
return False, "Session文件不存在"
|
||||
|
||||
try:
|
||||
data = json.loads(session_file.read_text(encoding="utf-8"))
|
||||
s = requests.Session()
|
||||
s.cookies.update(data.get("cookies", {}))
|
||||
r = s.get(get_base_url() + "/xtgl/index_initMenu.html",
|
||||
allow_redirects=False, timeout=8)
|
||||
|
||||
if r.status_code == 200:
|
||||
return True, None
|
||||
if r.status_code == 302 and 'login' in (r.headers.get('Location') or ''):
|
||||
return False, "Session已过期(302到登录页)"
|
||||
# 5xx/网关错误等不算 session 过期(避免上游抖动触发无谓重登)
|
||||
return False, f"教务系统响应异常 (HTTP {r.status_code})"
|
||||
except Exception as e:
|
||||
return False, f"检查Session时出错: {str(e)}"
|
||||
|
||||
@staticmethod
|
||||
def login_and_save(username, password, max_retries=10):
|
||||
"""
|
||||
登录并保存session
|
||||
返回: (success, error_msg, timing_dict_or_None)
|
||||
"""
|
||||
# 固定本次登录所用线路:重试期间全局线路可能切换,登录与写文件必须同线路
|
||||
login_base_url = get_base_url()
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
ocr_times = []
|
||||
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
result = login.login(username, password)
|
||||
if result.get('stop_retry'):
|
||||
# 密码到期等不可恢复错误:立即终止,避免白打剩余重试
|
||||
timing = {'attempts': attempt, 'ocr_ms': result.get('ocr_ms', 0)}
|
||||
return False, result.get('message', '登录失败(不可恢复)'), timing
|
||||
success = result.get('success', False)
|
||||
|
||||
if result.get('ocr_ms'):
|
||||
ocr_times.append(result['ocr_ms'])
|
||||
|
||||
if success:
|
||||
# 保存session
|
||||
data = {
|
||||
"cookies": dict(login.session.cookies),
|
||||
"headers": dict(login.session.headers),
|
||||
}
|
||||
SessionManager._save_session_atomic(username, data, login_base_url)
|
||||
timing = {
|
||||
'attempts': attempt,
|
||||
'ocr_ms': result.get('ocr_ms', 0),
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return True, None, timing
|
||||
else:
|
||||
if attempt < max_retries:
|
||||
time.sleep(0.5)
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
except Exception as e:
|
||||
if attempt < max_retries:
|
||||
time.sleep(0.5)
|
||||
login = JWXTLogin(base_url=login_base_url)
|
||||
else:
|
||||
timing = {
|
||||
'attempts': attempt,
|
||||
'ocr_ms': ocr_times[-1] if ocr_times else 0,
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return False, f"登录异常: {str(e)}", timing
|
||||
|
||||
timing = {
|
||||
'attempts': max_retries,
|
||||
'ocr_ms': ocr_times[-1] if ocr_times else 0,
|
||||
'ocr_avg_ms': int(sum(ocr_times) / len(ocr_times)) if len(ocr_times) > 1 else 0,
|
||||
}
|
||||
return False, f"登录失败,已尝试{max_retries}次", timing
|
||||
|
||||
@staticmethod
|
||||
def refresh_session(user, force=False):
|
||||
"""
|
||||
刷新指定用户的session(自动从 accounts.json 获取密码)
|
||||
|
||||
Args:
|
||||
user: User模型对象
|
||||
force: 是否强制刷新(忽略当前session是否有效)
|
||||
|
||||
返回: {
|
||||
'success': bool,
|
||||
'status': 'valid'/'refreshed'/'failed',
|
||||
'message': str,
|
||||
'error': str or None
|
||||
}
|
||||
"""
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(user_id=user.id, username=user.username)
|
||||
|
||||
if not jwxt_acc:
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': '未配置教务系统账号',
|
||||
'error': 'no_account'
|
||||
}
|
||||
|
||||
username = jwxt_acc['username']
|
||||
password = jwxt_acc['password']
|
||||
|
||||
# 如果不是强制刷新,先检查当前session
|
||||
if not force:
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
if is_valid:
|
||||
# 更新状态
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'valid',
|
||||
'message': 'Session仍然有效',
|
||||
'error': None
|
||||
}
|
||||
|
||||
# 执行登录
|
||||
success, error_msg, timing = SessionManager.login_and_save(
|
||||
username, password, max_retries=10
|
||||
)
|
||||
|
||||
if success:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'refreshed',
|
||||
'message': 'Session刷新成功',
|
||||
'error': None,
|
||||
'timing': timing or {},
|
||||
}
|
||||
else:
|
||||
user.session_status = 'invalid'
|
||||
user.session_error_msg = error_msg
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': error_msg,
|
||||
'error': 'login_failed',
|
||||
'timing': timing or {},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def refresh_session_with_password(user, password, force=False):
|
||||
"""
|
||||
使用明文密码刷新session(用于用户主动刷新)
|
||||
|
||||
返回: {
|
||||
'success': bool,
|
||||
'status': 'valid'/'refreshed'/'failed',
|
||||
'message': str,
|
||||
'error': str or None
|
||||
}
|
||||
"""
|
||||
username = user.jwxt_username or user.username
|
||||
|
||||
# 如果不是强制刷新,先检查当前session
|
||||
if not force:
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
if is_valid:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'valid',
|
||||
'message': 'Session仍然有效',
|
||||
'error': None
|
||||
}
|
||||
|
||||
# 执行登录
|
||||
success, error_msg, timing = SessionManager.login_and_save(
|
||||
username, password, max_retries=10
|
||||
)
|
||||
|
||||
if success:
|
||||
user.session_status = 'valid'
|
||||
user.session_updated_at = bj_now()
|
||||
user.session_error_msg = None
|
||||
return {
|
||||
'success': True,
|
||||
'status': 'refreshed',
|
||||
'message': 'Session刷新成功',
|
||||
'error': None,
|
||||
'timing': timing or {},
|
||||
}
|
||||
else:
|
||||
user.session_status = 'invalid'
|
||||
user.session_error_msg = error_msg
|
||||
return {
|
||||
'success': False,
|
||||
'status': 'failed',
|
||||
'message': error_msg,
|
||||
'error': 'login_failed',
|
||||
'timing': timing or {},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def reset_password_expiry(username, password):
|
||||
"""
|
||||
密码到期时,通过提交相同密码来刷新有效期。
|
||||
使用当前 session(即使有"无功能权限",cookies 仍有效)调用密码重置 API。
|
||||
|
||||
Args:
|
||||
username: 教务系统学号
|
||||
password: 教务系统密码(明文)
|
||||
|
||||
Returns:
|
||||
{'success': True/False, 'message': str}
|
||||
"""
|
||||
sf = SessionManager.get_session_file(username)
|
||||
if not sf.exists():
|
||||
return {'success': False, 'message': 'Session 文件不存在,无法重置密码'}
|
||||
|
||||
try:
|
||||
data = json.loads(sf.read_text(encoding='utf-8'))
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'Session 文件解析失败: {e}'}
|
||||
|
||||
s = requests.Session()
|
||||
s.cookies.update(data.get('cookies', {}))
|
||||
s.headers.update({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Referer': f'{get_base_url()}/xtgl/index_initMenu.html',
|
||||
})
|
||||
|
||||
try:
|
||||
# 1. 获取 RSA 公钥
|
||||
r = s.get(f"{get_base_url()}/xtgl/login_getPublicKey.html",
|
||||
params={"time": int(time.time() * 1000)}, timeout=10)
|
||||
r.raise_for_status()
|
||||
d = r.json()
|
||||
|
||||
# 2. RSA 加密密码
|
||||
modulus_int = int.from_bytes(base64.b64decode(d['modulus']), byteorder='big')
|
||||
exponent_int = int.from_bytes(base64.b64decode(d['exponent']), byteorder='big')
|
||||
key = RSA.construct((modulus_int, exponent_int))
|
||||
cipher = PKCS1_v1_5.new(key)
|
||||
encrypted = cipher.encrypt(password.encode('utf-8'))
|
||||
enc_pwd = base64.b64encode(encrypted).decode('utf-8')
|
||||
|
||||
# 3. 提交密码重置(旧密码=新密码,刷新有效期)
|
||||
r2 = s.post(
|
||||
f"{get_base_url()}/xtgl/mmgl_xgRsaMm.html",
|
||||
data={"ymm": enc_pwd, "mm": enc_pwd, "doType": "save"},
|
||||
timeout=15
|
||||
)
|
||||
if "成功" in r2.text:
|
||||
return {'success': True, 'message': '密码有效期已刷新'}
|
||||
else:
|
||||
return {'success': False, 'message': f'密码重置接口返回异常: {r2.text[:200]}'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': f'密码重置失败: {e}'}
|
||||
|
||||
@staticmethod
|
||||
def test_login(username, password, max_attempts=10):
|
||||
"""
|
||||
测试登录,用于注册时验证账号密码
|
||||
|
||||
返回: (success, message)
|
||||
"""
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
result = login.login(username, password)
|
||||
if result.get('success'):
|
||||
return True, "登录验证成功"
|
||||
else:
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.3)
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
except Exception as e:
|
||||
if attempt < max_attempts:
|
||||
time.sleep(0.3)
|
||||
login = JWXTLogin(base_url=get_base_url())
|
||||
else:
|
||||
return False, f"验证异常: {str(e)}"
|
||||
|
||||
return False, "账号或密码错误,请检查教务系统账号信息"
|
||||
|
||||
@staticmethod
|
||||
def batch_refresh(users, force=False, progress_callback=None):
|
||||
"""
|
||||
批量刷新session(自动从 accounts.json 获取密码)
|
||||
|
||||
Args:
|
||||
users: User对象列表
|
||||
force: 是否强制刷新
|
||||
progress_callback: 进度回调函数(user, result)
|
||||
|
||||
返回: {
|
||||
'total': int,
|
||||
'valid': int,
|
||||
'refreshed': int,
|
||||
'failed': int,
|
||||
'no_account': int,
|
||||
'details': list
|
||||
}
|
||||
"""
|
||||
results = {
|
||||
'total': len(users),
|
||||
'valid': 0,
|
||||
'refreshed': 0,
|
||||
'failed': 0,
|
||||
'no_account': 0,
|
||||
'details': []
|
||||
}
|
||||
|
||||
for user in users:
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(
|
||||
user_id=user.id, username=user.username
|
||||
)
|
||||
|
||||
if not jwxt_acc:
|
||||
result = {
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'status': 'no_account',
|
||||
'message': '未配置教务系统账号'
|
||||
}
|
||||
results['no_account'] += 1
|
||||
results['failed'] += 1
|
||||
else:
|
||||
# 执行刷新
|
||||
result = SessionManager.refresh_session(user, force=force)
|
||||
result['user_id'] = user.id
|
||||
result['username'] = user.username
|
||||
|
||||
if result['status'] == 'valid':
|
||||
results['valid'] += 1
|
||||
elif result['status'] == 'refreshed':
|
||||
results['refreshed'] += 1
|
||||
else:
|
||||
results['failed'] += 1
|
||||
|
||||
results['details'].append(result)
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(user, result)
|
||||
|
||||
time.sleep(0.2) # 避免请求过快
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def batch_refresh_running_users(db_session=None, school_id=None):
|
||||
"""
|
||||
刷新所有正在抢课中的用户的 session(一级优先)。
|
||||
用于 URL 切换后立即执行。
|
||||
|
||||
返回: {
|
||||
'total': int,
|
||||
'refreshed': int,
|
||||
'failed': int,
|
||||
'details': list
|
||||
}
|
||||
"""
|
||||
from app.models import GrabTask, User
|
||||
|
||||
# 查询有运行中抢课任务的用户
|
||||
query = User.query.join(GrabTask).filter(
|
||||
GrabTask.status == GrabTask.STATUS_RUNNING
|
||||
)
|
||||
if school_id:
|
||||
query = query.filter(User.school_id == school_id)
|
||||
running_users = query.all()
|
||||
|
||||
results = {
|
||||
'total': len(running_users),
|
||||
'refreshed': 0,
|
||||
'failed': 0,
|
||||
'details': []
|
||||
}
|
||||
|
||||
for user in running_users:
|
||||
from app.url_manager import push_school, pop_school
|
||||
push_school(user.school_id)
|
||||
try:
|
||||
result = SessionManager.refresh_session(user, force=True)
|
||||
finally:
|
||||
pop_school()
|
||||
result['user_id'] = user.id
|
||||
result['username'] = user.username
|
||||
|
||||
if result['status'] == 'refreshed':
|
||||
results['refreshed'] += 1
|
||||
else:
|
||||
results['failed'] += 1
|
||||
|
||||
results['details'].append(result)
|
||||
time.sleep(0.2) # 避免请求过快
|
||||
|
||||
if running_users:
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.info(
|
||||
f"[session_manager] 已刷新 {results['refreshed']}/{results['total']} "
|
||||
f"个抢课中的用户 session"
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def ensure_session_valid(user, auto_refresh=True):
|
||||
"""
|
||||
确保用户session有效,如果过期则自动刷新
|
||||
|
||||
Args:
|
||||
user: User模型对象
|
||||
auto_refresh: 是否自动刷新
|
||||
|
||||
返回: (is_valid, error_msg)
|
||||
"""
|
||||
# 获取教务系统账号
|
||||
jwxt_acc = AccountManager.get_jwxt_account(
|
||||
user_id=user.id, username=user.username
|
||||
)
|
||||
|
||||
if not jwxt_acc:
|
||||
return False, "未配置教务系统账号"
|
||||
|
||||
username = jwxt_acc['username']
|
||||
|
||||
# 检查session
|
||||
is_valid, error_msg = SessionManager.is_session_valid(username)
|
||||
|
||||
if is_valid:
|
||||
return True, None
|
||||
|
||||
# 需要刷新
|
||||
if not auto_refresh:
|
||||
return False, error_msg
|
||||
|
||||
# 自动刷新
|
||||
result = SessionManager.refresh_session(user, force=True)
|
||||
|
||||
if result['success']:
|
||||
return True, None
|
||||
else:
|
||||
return False, result['message']
|
||||
Reference in New Issue
Block a user