Files

450 lines
19 KiB
Python
Raw Permalink 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.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据库模型定义
"""
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from app.time_utils import now as _now, to_iso
import json
db = SQLAlchemy()
class User(db.Model):
"""用户模型 - 网站账号(与教务系统账号分离)"""
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False, index=True, comment='网站登录用户名')
password_hash = db.Column(db.String(256), nullable=False, comment='网站登录密码哈希')
# 教务系统账号信息(仅存储学号和姓名,密码在 accounts.json)
jwxt_username = db.Column(db.String(20), nullable=True, comment='教务系统学号')
jwxt_name = db.Column(db.String(50), nullable=True, comment='姓名')
school_id = db.Column(db.String(40), nullable=True, default='sdmu', comment='注册时选择的学校,不允许修改')
# Session状态
session_status = db.Column(db.String(20), default='unknown', comment='session状态: valid/invalid/unknown')
session_updated_at = db.Column(db.DateTime, nullable=True, comment='session最后更新时间')
session_error_msg = db.Column(db.Text, nullable=True, comment='session错误信息')
is_admin = db.Column(db.Boolean, default=False, comment='是否管理员')
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
last_login = db.Column(db.DateTime, nullable=True, comment='最后登录时间')
is_active = db.Column(db.Boolean, default=True, comment='是否激活')
# AI 每日 token 用量上限(输入+输出)。NULL=用全局默认值,0=不限制
ai_daily_limit = db.Column(db.BigInteger, nullable=True, comment='AI 每日 token 上限:NULL=全局默认,0=不限制')
# 关联关系
tasks = db.relationship('GrabTask', backref='user', lazy='dynamic', cascade='all, delete-orphan')
logs = db.relationship('GrabLog', backref='user', lazy='dynamic', cascade='all, delete-orphan')
def set_password(self, password):
"""设置网站登录密码"""
self.password_hash = generate_password_hash(password)
def check_password(self, password):
"""验证网站登录密码"""
if self.password_hash is None:
return False
return check_password_hash(self.password_hash, password)
def get_id(self):
"""Flask-Login 必需的方法"""
return str(self.id)
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_jwxt_account(self):
"""获取教务系统账号(从 accounts.json)"""
from app.account_manager import get_jwxt_account
return get_jwxt_account(user_id=self.id, username=self.username)
def has_jwxt_account(self):
"""检查是否配置了教务系统账号"""
return self.get_jwxt_account() is not None
def to_dict(self):
"""转换为字典"""
return {
'id': self.id,
'username': self.username,
'jwxt_username': self.jwxt_username,
'jwxt_name': self.jwxt_name,
'school_id': self.school_id or 'sdmu',
'has_jwxt_account': self.has_jwxt_account(),
'session_status': self.session_status,
'session_updated_at': to_iso(self.session_updated_at),
'session_error_msg': self.session_error_msg,
'is_admin': self.is_admin,
'created_at': to_iso(self.created_at),
'last_login': to_iso(self.last_login),
'is_active': self.is_active
}
def to_dict_admin(self):
"""管理员查看的完整信息"""
data = self.to_dict()
jwxt_acc = self.get_jwxt_account()
data['has_jwxt_password'] = jwxt_acc is not None
return data
class GrabTask(db.Model):
"""抢课任务模型"""
__tablename__ = 'grab_tasks'
# 任务状态
STATUS_PENDING = 'pending' # 待执行
STATUS_RUNNING = 'running' # 执行中
STATUS_SUCCESS = 'success' # 成功
STATUS_FAILED = 'failed' # 失败
STATUS_CANCELLED = 'cancelled' # 已取消
STATUS_EXPIRED = 'expired' # 已过期
# 任务类型
TYPE_IMMEDIATE = 'immediate' # 立即抢课
TYPE_SCHEDULED = 'scheduled' # 定时抢课
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
# 课程信息
course_name = db.Column(db.String(100), nullable=False, comment='课程名称')
course_id = db.Column(db.String(50), nullable=False, comment='课程ID(jxb_id)')
teacher_name = db.Column(db.String(50), nullable=True, comment='教师姓名')
credit = db.Column(db.String(10), nullable=True, comment='学分')
class_info = db.Column(db.String(100), nullable=True, comment='班级信息')
# 抢课所需完整参数(对齐 xk_api.py)
do_jxb_id = db.Column(db.String(500), nullable=True, comment='加密ID/志愿场次ID')
kch_id = db.Column(db.String(50), nullable=True, comment='课程号ID')
jxbzls = db.Column(db.String(10), default='0', comment='教学班总量/志愿序号')
kklxdm = db.Column(db.String(10), nullable=True, comment='课程类型代码')
# 自定义规则(JSON: {"on_has_vacancy": [{"action": "drop_course", ...}]})
rules = db.Column(db.Text, nullable=True, comment='自定义规则(JSON)')
# 任务配置
task_type = db.Column(db.String(20), default=TYPE_IMMEDIATE, comment='任务类型')
scheduled_time = db.Column(db.DateTime, nullable=True, comment='定时执行时间')
# 任务状态
status = db.Column(db.String(20), default=STATUS_PENDING, index=True, comment='任务状态')
retry_count = db.Column(db.Integer, default=0, comment='重试次数')
max_retries = db.Column(db.Integer, default=100, comment='最大重试次数')
# 执行结果
result_message = db.Column(db.Text, nullable=True, comment='结果消息')
started_at = db.Column(db.DateTime, nullable=True, comment='开始时间')
completed_at = db.Column(db.DateTime, nullable=True, comment='完成时间')
# 时间戳
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now, comment='更新时间')
# 关联关系
logs = db.relationship('GrabLog', backref='task', lazy='dynamic', cascade='all, delete-orphan')
def to_dict(self):
"""转换为字典"""
return {
'id': self.id,
'user_id': self.user_id,
'username': self.user.username if self.user else None,
'course_name': self.course_name,
'course_id': self.course_id,
'teacher_name': self.teacher_name,
'credit': self.credit,
'class_info': self.class_info,
'do_jxb_id': self.do_jxb_id,
'kch_id': self.kch_id,
'jxbzls': self.jxbzls,
'kklxdm': self.kklxdm,
'rules': json.loads(self.rules) if self.rules else None,
'task_type': self.task_type,
'scheduled_time': to_iso(self.scheduled_time),
'status': self.status,
'retry_count': self.retry_count,
'max_retries': self.max_retries,
'result_message': self.result_message,
'started_at': to_iso(self.started_at),
'completed_at': to_iso(self.completed_at),
'created_at': to_iso(self.created_at),
'updated_at': to_iso(self.updated_at)
}
class GrabLog(db.Model):
"""抢课日志模型"""
__tablename__ = 'grab_logs'
# 日志级别
LEVEL_INFO = 'info'
LEVEL_WARNING = 'warning'
LEVEL_ERROR = 'error'
LEVEL_SUCCESS = 'success'
id = db.Column(db.Integer, primary_key=True)
task_id = db.Column(db.Integer, db.ForeignKey('grab_tasks.id'), nullable=False, index=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
# 日志内容
level = db.Column(db.String(20), default=LEVEL_INFO, comment='日志级别')
message = db.Column(db.Text, nullable=False, comment='日志消息')
detail = db.Column(db.Text, nullable=True, comment='详细内容(JSON)')
# 时间戳
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
def to_dict(self):
"""转换为字典"""
return {
'id': self.id,
'task_id': self.task_id,
'user_id': self.user_id,
'username': self.user.username if self.user else None,
'level': self.level,
'message': self.message,
'detail': self.detail,
'created_at': to_iso(self.created_at)
}
class AiConversation(db.Model):
"""每个网站账号的一条选课 AI 会话。"""
__tablename__ = 'ai_conversations'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, unique=True, index=True)
created_at = db.Column(db.DateTime, default=_now, nullable=False)
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now, nullable=False)
messages = db.relationship(
'AiConversationMessage', backref='conversation', lazy='dynamic',
cascade='all, delete-orphan'
)
class AiConversationMessage(db.Model):
"""AI 会话文本。工具调用参数与 API Key 均不写入此表。"""
__tablename__ = 'ai_conversation_messages'
id = db.Column(db.Integer, primary_key=True)
conversation_id = db.Column(db.Integer, db.ForeignKey('ai_conversations.id'), nullable=False, index=True)
role = db.Column(db.String(16), nullable=False, comment='user / assistant')
content = db.Column(db.Text, nullable=False)
created_at = db.Column(db.DateTime, default=_now, nullable=False)
def to_dict(self):
return {
'id': self.id,
'role': self.role,
'content': self.content,
'created_at': to_iso(self.created_at),
}
class AiUsageLog(db.Model):
"""AI 每次模型调用的 token 用量(输入/输出),用于管理端统计与每日限额。"""
__tablename__ = 'ai_usage_logs'
__table_args__ = (
db.Index('idx_ai_usage_user_time', 'user_id', 'created_at'),
)
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
model = db.Column(db.String(100), nullable=True, comment='模型名')
input_tokens = db.Column(db.BigInteger, nullable=False, default=0)
output_tokens = db.Column(db.BigInteger, nullable=False, default=0)
created_at = db.Column(db.DateTime, default=_now, nullable=False)
def to_dict(self):
return {
'id': self.id,
'user_id': self.user_id,
'model': self.model,
'input_tokens': self.input_tokens,
'output_tokens': self.output_tokens,
'created_at': to_iso(self.created_at),
}
class AiScheduledTask(db.Model):
"""AI 定时任务:到点后由调度器自动、无人值守地执行一次用户委托的 AI 指令。
执行期间写操作自动视为用户已确认(创建任务即委托);用量照常记录,
但执行不受每日限额中断(体验优先)。
"""
__tablename__ = 'ai_scheduled_tasks'
__table_args__ = (
db.Index('idx_ai_sched_due', 'status', 'scheduled_at'),
)
STATUS_PENDING = 'pending'
STATUS_RUNNING = 'running'
STATUS_SUCCESS = 'success'
STATUS_FAILED = 'failed'
STATUS_CANCELLED = 'cancelled'
STATUS_ENDED = 'ended' # 重复任务到期/达次数上限自动结束
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
conversation_id = db.Column(db.Integer, nullable=True, comment='结果写回的会话')
instruction = db.Column(db.Text, nullable=False, comment='到点要执行的完整指令')
scheduled_at = db.Column(db.DateTime, nullable=False, comment='下次执行时间(北京时间)')
repeat_interval = db.Column(db.BigInteger, nullable=True, comment='重复间隔(秒),NULL=一次性')
repeat_until = db.Column(db.DateTime, nullable=True, comment='重复截止时间,到期自动结束')
run_count = db.Column(db.Integer, nullable=True, comment='已执行次数')
status = db.Column(db.String(20), default=STATUS_PENDING, nullable=False, index=True)
result = db.Column(db.Text, nullable=True, comment='AI 最终输出(重复任务为最近一次)')
error = db.Column(db.String(500), nullable=True, comment='失败/取消原因')
created_at = db.Column(db.DateTime, default=_now, nullable=False)
claimed_at = db.Column(db.DateTime, nullable=True, comment='调度器认领时间,用于中断恢复')
executed_at = db.Column(db.DateTime, nullable=True)
def to_dict(self):
return {
'id': self.id,
'user_id': self.user_id,
'conversation_id': self.conversation_id,
'instruction': self.instruction,
'scheduled_at': to_iso(self.scheduled_at),
'repeat_interval': self.repeat_interval,
'repeat_until': to_iso(self.repeat_until),
'run_count': self.run_count or 0,
'status': self.status,
'result': self.result,
'error': self.error,
'created_at': to_iso(self.created_at),
'executed_at': to_iso(self.executed_at),
}
class SystemConfig(db.Model):
"""系统配置模型"""
__tablename__ = 'system_configs'
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String(50), unique=True, nullable=False, comment='配置键')
value = db.Column(db.Text, nullable=True, comment='配置值')
description = db.Column(db.String(200), nullable=True, comment='配置说明')
updated_at = db.Column(db.DateTime, default=_now, onupdate=_now)
# ── 内存缓存(每请求热路径,避免频繁查 SQLite)──
_config_cache: dict = {}
_config_cache_lock = None # 延迟初始化(db.Model 定义阶段 threading 还没导入)
_CONFIG_CACHE_TTL = 30 # 秒
@staticmethod
def get(key, default=None):
"""获取配置值(带 30 秒内存缓存)"""
import time as _time
import threading as _threading
if SystemConfig._config_cache_lock is None:
SystemConfig._config_cache_lock = _threading.Lock()
now = _time.time()
with SystemConfig._config_cache_lock:
entry = SystemConfig._config_cache.get(key)
if entry is not None:
value, ts = entry
if now - ts < SystemConfig._CONFIG_CACHE_TTL:
return value if value is not None else default
config = SystemConfig.query.filter_by(key=key).first()
value = config.value if config else None
with SystemConfig._config_cache_lock:
SystemConfig._config_cache[key] = (value, now)
return value if value is not None else default
@staticmethod
def set(key, value, description=None):
"""设置配置值(同时清除缓存)"""
config = SystemConfig.query.filter_by(key=key).first()
if config:
config.value = value
else:
config = SystemConfig(key=key, value=value, description=description)
db.session.add(config)
db.session.commit()
# 清除该 key 的缓存
import threading as _threading
if SystemConfig._config_cache_lock is None:
SystemConfig._config_cache_lock = _threading.Lock()
with SystemConfig._config_cache_lock:
SystemConfig._config_cache.pop(key, None)
class IPBan(db.Model):
"""IP封禁模型"""
__tablename__ = 'ip_bans'
# 封禁类型
TYPE_IP = 'ip' # 单个IP
TYPE_CIDR = 'cidr' # IP段 (CIDR)
TYPE_COUNTRY = 'country' # 国家/地区代码
id = db.Column(db.Integer, primary_key=True)
ban_type = db.Column(db.String(20), default=TYPE_IP, nullable=False, comment='封禁类型: ip/cidr/country')
value = db.Column(db.String(100), nullable=False, index=True, comment='封禁值: IP/CIDR/国家代码')
reason = db.Column(db.String(200), nullable=True, comment='封禁原因')
is_permanent = db.Column(db.Boolean, default=False, comment='是否永久封禁')
expires_at = db.Column(db.DateTime, nullable=True, comment='解封时间(NULL=永久)')
created_at = db.Column(db.DateTime, default=_now, comment='创建时间')
created_by = db.Column(db.String(50), nullable=True, comment='操作者(admin/auto)')
class IPAccessLog(db.Model):
"""IP访问日志模型"""
__tablename__ = 'ip_access_logs'
id = db.Column(db.Integer, primary_key=True)
ip = db.Column(db.String(50), nullable=False, index=True, comment='访问IP')
country = db.Column(db.String(10), nullable=True, comment='国家代码')
region = db.Column(db.String(50), nullable=True, comment='省/州')
city = db.Column(db.String(50), nullable=True, comment='城市')
isp = db.Column(db.String(100), nullable=True, comment='运营商')
method = db.Column(db.String(10), nullable=True, comment='HTTP方法')
path = db.Column(db.String(500), nullable=True, comment='请求路径')
status_code = db.Column(db.Integer, nullable=True, comment='响应状态码')
user_agent = db.Column(db.String(500), nullable=True, comment='UserAgent')
blocked = db.Column(db.Boolean, default=False, comment='是否被拦截')
block_reason = db.Column(db.String(100), nullable=True, comment='拦截原因')
created_at = db.Column(db.DateTime, default=_now, index=True, comment='访问时间')
def to_dict(self):
return {
'id': self.id,
'ip': self.ip,
'country': self.country,
'region': self.region,
'city': self.city,
'isp': self.isp,
'method': self.method,
'path': self.path,
'status_code': self.status_code,
'user_agent': self.user_agent,
'blocked': self.blocked,
'block_reason': self.block_reason,
'created_at': to_iso(self.created_at)
}
class LoginAttempt(db.Model):
"""登录尝试记录(用于频率限制)"""
__tablename__ = 'login_attempts'
id = db.Column(db.Integer, primary_key=True)
ip = db.Column(db.String(50), nullable=False, index=True, comment='来源IP')
username = db.Column(db.String(50), nullable=True, comment='尝试的用户名')
success = db.Column(db.Boolean, default=False, comment='是否成功')
created_at = db.Column(db.DateTime, default=_now, index=True, comment='时间')