- IMAP服务器 111.229.206.54 只开放143端口(非SSL),993不通 - 默认配置改为端口143、ssl=False - EmailVerifier 增加 use_ssl 参数,支持 IMAP4 和 IMAP4_SSL - Account 模型增加 email_imap_ssl 字段 - 数据库迁移:新增列 + 修正旧数据端口和SSL设置 - 导入账号时自动填充 ssl 配置 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
88 lines
2.8 KiB
Python
88 lines
2.8 KiB
Python
"""数据库引擎与会话管理"""
|
||
|
||
from pathlib import Path
|
||
from sqlalchemy import create_engine
|
||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||
|
||
DB_PATH = Path(__file__).parent.parent.parent / "data" / "web.db"
|
||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
|
||
engine = create_engine(
|
||
f"sqlite:///{DB_PATH}",
|
||
connect_args={"check_same_thread": False},
|
||
echo=False,
|
||
)
|
||
|
||
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||
Base = declarative_base()
|
||
|
||
|
||
def get_db():
|
||
"""FastAPI 依赖:提供数据库会话,请求结束自动关闭。"""
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
def init_db():
|
||
"""建表 + 写入初始数据。"""
|
||
Base.metadata.create_all(bind=engine)
|
||
_migrate()
|
||
_seed()
|
||
|
||
|
||
def _migrate():
|
||
"""数据库迁移:为已有表添加新列。"""
|
||
from sqlalchemy import text
|
||
with engine.connect() as conn:
|
||
# 检查 accounts.tag 列是否存在
|
||
result = conn.execute(text("PRAGMA table_info(accounts)"))
|
||
columns = [row[1] for row in result]
|
||
if 'tag' not in columns:
|
||
conn.execute(text("ALTER TABLE accounts ADD COLUMN tag VARCHAR(64) DEFAULT ''"))
|
||
conn.commit()
|
||
|
||
# 检查 users.custom_permissions 列是否存在
|
||
result = conn.execute(text("PRAGMA table_info(users)"))
|
||
columns = [row[1] for row in result]
|
||
if 'custom_permissions' not in columns:
|
||
conn.execute(text("ALTER TABLE users ADD COLUMN custom_permissions JSON DEFAULT NULL"))
|
||
conn.commit()
|
||
|
||
# 检查 accounts.email_imap_ssl 列是否存在
|
||
result = conn.execute(text("PRAGMA table_info(accounts)"))
|
||
columns = [row[1] for row in result]
|
||
if 'email_imap_ssl' not in columns:
|
||
# 旧数据端口993的默认True(SSL),其他端口默认False
|
||
conn.execute(text("ALTER TABLE accounts ADD COLUMN email_imap_ssl BOOLEAN DEFAULT 1"))
|
||
conn.commit()
|
||
# 修正旧数据中使用 111.229.206.54 的账号:端口改为143,SSL改为False
|
||
conn.execute(text(
|
||
"UPDATE accounts SET email_imap_port = 143, email_imap_ssl = 0 "
|
||
"WHERE email_imap_server = '111.229.206.54'"
|
||
))
|
||
conn.commit()
|
||
|
||
|
||
def _seed():
|
||
"""写入默认超管账号和角色。"""
|
||
from .models import User
|
||
from .security import hash_password
|
||
|
||
db = SessionLocal()
|
||
try:
|
||
if not db.query(User).first():
|
||
admin = User(
|
||
username="admin",
|
||
password_hash=hash_password("admin123"),
|
||
role="super_admin",
|
||
is_active=True,
|
||
remark="默认超级管理员",
|
||
)
|
||
db.add(admin)
|
||
db.commit()
|
||
finally:
|
||
db.close()
|