初版:教务抢课系统 jwxt(从线上实例导出)

This commit is contained in:
deploy
2026-10-29 12:54:56 +08:00
commit 4adf153426
106 changed files with 50288 additions and 0 deletions
+340
View File
@@ -0,0 +1,340 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Flask应用工厂
"""
import os
import random
import time
import threading
import urllib.request
from flask import Flask, g
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_cors import CORS
from app.config import config
from app.models import db, User
from app.grab_engine import grab_engine
# 初始化扩展
login_manager = LoginManager()
def create_app(config_name='default'):
"""应用工厂函数"""
app = Flask(__name__,
template_folder='templates',
static_folder='static')
# 加载配置
app.config.from_object(config[config_name])
# 确保 Tailwind CSS 本地缓存
_ensure_tailwind_cache(app.static_folder)
# 初始化扩展
db.init_app(app)
login_manager.init_app(app)
CORS(app)
# AI 选课助手使用原生 WebSocket,避免 HTTP 响应流被代理或浏览器缓冲。
from flask_sock import Sock
sock = Sock(app)
# 信任Nginx反向代理头,让request.remote_addr返回真实IP
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=0, x_prefix=0)
# 配置登录管理
login_manager.login_view = 'main.login'
login_manager.login_message = '请先登录'
login_manager.login_message_category = 'warning'
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# 注册蓝图
from app.routes import main_bp, api_bp
app.register_blueprint(main_bp)
app.register_blueprint(api_bp, url_prefix='/api')
from app.ai_websocket import register_ai_websocket
register_ai_websocket(sock)
# ── 品牌注入:网页标题/题头/favicon 按访问者学校自适应 ──
# 学生 → "{学校缩写}教务助手" + 学校 ICO;登录页/管理面板等无法或
# 不需要挂学校的场景 → 通用"教务助手" + 默认图标
@app.context_processor
def _inject_brand():
from flask_login import current_user
from app.school_manager import school_abbr, school_favicon, DEFAULT_SCHOOL_ID
brand, favicon = '教务助手', None
try:
if current_user.is_authenticated and not current_user.is_admin:
school_id = current_user.school_id or DEFAULT_SCHOOL_ID
brand = f"{school_abbr(school_id)}教务助手"
favicon = school_favicon(school_id)
except Exception:
pass
default_favicon = (
"data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'"
"%20viewBox='0%200%20100%20100'%3E%3Ctext%20y='.9em'%20font-size='90'%3E"
"%F0%9F%8E%93%3C/text%3E%3C/svg%3E"
)
return {'brand_name': brand, 'brand_favicon': favicon or default_favicon}
# 注册IP访问控制中间件
from app.ip_middleware import init_ip_middleware
init_ip_middleware(app)
# ── 请求计时中间件(为所有 JSON 响应注入 _timing)──
@app.before_request
def _timing_before():
g._request_start = time.perf_counter()
@app.after_request
def _timing_after(response):
if not hasattr(g, '_request_start'):
return response
total_ms = int((time.perf_counter() - g._request_start) * 1000)
# 只对 JSON 响应注入计时
ct = response.content_type or ''
if 'application/json' not in ct:
return response
try:
import json
data = json.loads(response.get_data(as_text=True))
if isinstance(data, dict):
if '_timing' not in data:
# 没有 _timing 的 JSON 响应(非 with_session_retry 路由)
data['_timing'] = {
'backend_total_ms': total_ms,
'jwxt_api_ms': 0,
'source': 'request_total',
}
else:
# 已有 _timing(来自 with_session_retry),补充请求总耗时
data['_timing']['request_total_ms'] = total_ms
response.set_data(json.dumps(data, ensure_ascii=False))
except (json.JSONDecodeError, UnicodeDecodeError, TypeError):
pass # 非标准 JSON,不管
return response
# 初始化抢课引擎
grab_engine.init_app(app)
# 创建数据库表
with app.app_context():
db.create_all()
# 先补全旧数据库缺失的列(兼容 MySQL / SQLite),
# 再初始化数据:模型列必须先与库结构对齐,否则任何 ORM 查询都会报 Unknown column。
_auto_upgrade_schema(app)
_init_admin_user(app)
# 启动抢课引擎(在数据库表创建之后)
grab_engine.start()
# 启动 AI 定时任务调度器(到点自动执行用户委托的 AI 指令)
from app.ai_scheduler import init_scheduler
init_scheduler(app)
# 清理服务器重启前中断的课程索引文件
from app.jwxt_api import JwxtApi
JwxtApi.cleanup_stale_index()
# 初始化 URL 地址管理器:选最优地址 + 定时检测切换
from app.url_manager import switch_if_needed, get_base_url
from app.school_manager import list_schools
try:
switched, old, new = switch_if_needed()
print(f"[url_manager] 初始地址: {get_base_url()}"
+ (f" (已从 {old} 切换)" if switched else ""))
except Exception as e:
print(f"[url_manager] 初始化地址失败: {e},使用默认: {get_base_url()}")
# 多线路 Session 预热(管理端按学校开关,任一学校开启即启动后台线程)
from app.multi_line import any_enabled as _ml_any, start_background as _ml_start
if _ml_any():
_ml_start(prelogin=True)
# 后台线程:每 60 秒检测一次地址延迟
def _url_monitor():
import time
from app.url_manager import switch_if_needed
from app.session_manager import SessionManager
from app.multi_line import is_enabled as ml_enabled
while True:
time.sleep(60)
try:
from app.school_manager import list_schools
for school in list_schools():
switched, old_url, new_url = switch_if_needed(school['id'])
if switched and not ml_enabled(school['id']):
# 刷新抢课中的用户的 session
with app.app_context():
SessionManager.batch_refresh_running_users(school_id=school['id'])
except Exception:
pass
t = threading.Thread(target=_url_monitor, daemon=True)
t.start()
# 后台线程:每 2 小时检查并刷新所有用户的 session
SESSION_REFRESH_INTERVAL = 2 * 3600 # 2 小时
def _session_refresh_loop():
import time
import logging
logger = logging.getLogger(__name__)
from app.session_manager import SessionManager
from app.account_manager import AccountManager
from app.time_utils import now as bj_now
# 首次延迟随机 5~30 分钟,避免启动时突发请求
first_delay = random.uniform(300, 1800)
logger.info(f"[session_refresh] 首次 session 检查延迟 {first_delay:.0f} 秒后执行")
time.sleep(first_delay)
while True:
try:
now_hour = bj_now().hour
# 夜间 00:00~05:00 跳过
if 0 <= now_hour < 5:
time.sleep(600)
continue
from app.multi_line import is_enabled as ml_enabled, is_xk_mode
accounts = AccountManager.get_all_accounts()
for acc in accounts:
username = acc.get('jwxt_username') or ''
if not username:
continue
acc_school = acc.get('school_id') or 'sdmu'
# 选课模式(按学校):该校暂停非核心的全量 session 刷新
if is_xk_mode(acc_school):
continue
# 多线路预热(按学校):本循环只会用"全局线路"校验/重登,
# 会给固定了其他线路的用户写错 cookie;该校的预热/保活/回填
# 由 multi_line 的 keepalive 线程统一负责,这里按学校让路
if ml_enabled(acc_school):
continue
try:
from app.url_manager import push_school, pop_school
push_school(acc_school)
valid, _ = SessionManager.is_session_valid(username)
if not valid:
password = acc.get('jwxt_password', '')
if password:
logger.info(f"[session_refresh] session 已过期,正在刷新: {username}")
SessionManager.login_and_save(username, password)
except Exception as e:
logger.warning(f"[session_refresh] 检查失败 {username}: {e}")
finally:
pop_school()
logger.info(f"[session_refresh] 完成一轮 session 检查({len(accounts)} 个用户)")
except Exception as e:
logger.error(f"[session_refresh] 循环异常: {e}")
time.sleep(SESSION_REFRESH_INTERVAL)
t2 = threading.Thread(target=_session_refresh_loop, daemon=True, name="session-refresh")
t2.start()
# 启动邮件解封后台线程
from app.ip_manager import start_email_unban_checker
start_email_unban_checker(app)
return app
def _init_admin_user(app):
"""初始化管理员账号"""
admin = User.query.filter_by(username=app.config['ADMIN_USERNAME']).first()
if not admin:
admin = User(
username=app.config['ADMIN_USERNAME'],
is_admin=True,
is_active=True
)
admin.set_password(app.config['ADMIN_PASSWORD'])
db.session.add(admin)
db.session.commit()
print(f"[OK] 管理员账号已创建: {app.config['ADMIN_USERNAME']}")
def _auto_upgrade_schema(app):
"""自动给旧数据库补上模型新增的列(兼容 MySQL / SQLite)"""
from sqlalchemy import inspect, text
from app.models import GrabTask
with app.app_context():
inspector = inspect(db.engine)
# 确保新表存在(ai_usage_logs 等)
db.create_all()
# 模型新增的列(只补可空列,避免 NOT NULL 约束冲突)
new_columns = {
'grab_tasks': {'rules': 'TEXT'},
'users': {'ai_daily_limit': 'BIGINT', 'school_id': 'VARCHAR(40)'},
'ai_scheduled_tasks': {
'repeat_interval': 'BIGINT',
'repeat_until': 'DATETIME',
'run_count': 'INTEGER',
},
}
for table, columns in new_columns.items():
try:
existing_cols = {col['name'] for col in inspector.get_columns(table)}
except Exception:
continue # 表不存在,db.create_all() 会建
for col, col_type in columns.items():
if col in existing_cols:
continue
try:
db.session.execute(text(f'ALTER TABLE {table} ADD COLUMN {col} {col_type}'))
db.session.commit()
print(f"[DB] 新增列 {table}.{col} ({col_type})")
except Exception as e:
print(f"[!] 新增列 {table}.{col} 失败: {e}")
db.session.rollback()
# 旧版所有账号归属山东管理学院;只填空值,绝不覆盖已注册的新学校。
db.session.execute(text("UPDATE users SET school_id = 'sdmu' WHERE school_id IS NULL OR school_id = ''"))
db.session.commit()
def _ensure_tailwind_cache(static_path):
"""确保 Tailwind CSS 本地缓存存在,优先使用本地文件"""
tailwind_path = os.path.join(static_path, 'tailwind.min.css')
cdn_url = 'https://cdn.tailwindcss.com/3.4.1'
# 检查本地缓存是否存在且有效(>100KB)
if os.path.exists(tailwind_path) and os.path.getsize(tailwind_path) > 100_000:
print(f"[OK] Tailwind CSS 本地缓存已就绪 ({os.path.getsize(tailwind_path)//1024}KB)")
return
# 本地缓存无效,尝试从 CDN 下载
print("[*] 正在下载 Tailwind CSS(首次启动)...")
for attempt in range(3):
try:
req = urllib.request.Request(cdn_url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
})
with urllib.request.urlopen(req, timeout=30) as resp:
content = resp.read()
if len(content) > 100_000:
with open(tailwind_path, 'wb') as f:
f.write(content)
print(f"[OK] Tailwind CSS 已缓存到本地 ({len(content)//1024}KB)")
return
except Exception as e:
print(f"[!] 下载失败(第{attempt+1}次): {e}")
if attempt < 2:
time.sleep(2)
print("[!] Tailwind CSS 下载失败,将使用 CDN")