refactor: 移除 SMTP 相关代码,简化用户创建流程,更新文档

This commit is contained in:
2026-04-13 12:27:14 +08:00
parent 919c561629
commit 66c254e0ff
13 changed files with 41 additions and 466 deletions
+1 -2
View File
@@ -2,7 +2,7 @@
import typer
from tjhlp.commands import labels, notify, orgs, repos, setup, stats, users, webhooks
from tjhlp.commands import labels, orgs, repos, setup, stats, users, webhooks
app = typer.Typer(
name="tjhlp",
@@ -17,7 +17,6 @@ app.add_typer(repos.app, name="repos", help="仓库管理")
app.add_typer(webhooks.app, name="webhooks", help="Webhook 管理")
app.add_typer(labels.app, name="labels", help="Label 管理")
app.add_typer(stats.app, name="stats", help="Issue 统计")
app.add_typer(notify.app, name="notify", help="邮件通知")
if __name__ == "__main__":
-117
View File
@@ -1,117 +0,0 @@
"""notify 命令: 通过 SMTP 发送账号凭据邮件"""
from __future__ import annotations
import csv
import smtplib
import ssl
import time
from email.mime.text import MIMEText
from pathlib import Path
import typer
from rich.console import Console
from rich.panel import Panel
from tjhlp.config import get_gitea_config, get_smtp_config
from tjhlp.models import CredentialRecord
app = typer.Typer(no_args_is_help=True)
console = Console()
def _build_email_text(cred: CredentialRecord, gitea_url: str) -> str:
"""构建纯文本邮件正文"""
return f"""\
同济大学高级语言程序设计 - 答疑平台账号
{"=" * 40}
{cred.name}同学/老师, 你好!
你的课程答疑平台账号已创建, 请使用以下信息登录:
平台地址: {gitea_url}
用户名: {cred.username}
初始密码: {cred.password}
首次登录后请立即修改密码。
如有问题, 请联系助教。
"""
def _read_credentials_csv(filepath: Path) -> list[CredentialRecord]:
"""读取凭据 CSV 文件"""
records: list[CredentialRecord] = []
with open(filepath, encoding="utf-8-sig") as f:
reader = csv.DictReader(f)
for row in reader:
records.append(CredentialRecord.model_validate(row))
return records
@app.command("send-credentials")
def send_credentials(
file: Path = typer.Option(..., "--file", "-f", help="凭据 CSV 文件路径(由 users create 生成)"),
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览邮件内容, 不实际发送"),
batch_size: int = typer.Option(
10, "--batch-size", help="每批发送数量, 批次间暂停 2 秒(避免触发 SMTP 限制)"
),
) -> None:
"""通过 SMTP 向同济邮箱发送账号密码邮件"""
if not file.exists():
console.print(f"[red]文件不存在: {file}[/red]")
raise typer.Exit(code=1)
gitea_cfg = get_gitea_config()
credentials = _read_credentials_csv(file)
console.print(f"读取到 {len(credentials)} 条凭据记录")
if dry_run:
# 预览第一封邮件
if credentials:
cred = credentials[0]
text = _build_email_text(cred, str(gitea_cfg.url))
console.print(Panel(text, title=f"邮件预览 -> {cred.email}", border_style="blue"))
console.print(f"\n[yellow]dry-run 模式, 共 {len(credentials)} 封邮件待发送[/yellow]")
return
smtp_cfg = get_smtp_config()
from_addr = smtp_cfg.from_addr or smtp_cfg.user
stats = {"sent": 0, "failed": 0}
context = ssl.create_default_context()
try:
with smtplib.SMTP_SSL(smtp_cfg.host, smtp_cfg.port, context=context) as server:
server.login(smtp_cfg.user, smtp_cfg.password.get_secret_value())
console.print(f"[green]已连接 SMTP 服务器 {smtp_cfg.host}[/green]")
for i, cred in enumerate(credentials, 1):
msg = MIMEText(_build_email_text(cred, str(gitea_cfg.url)), "plain", "utf-8")
msg["Subject"] = "同济大学高级语言程序设计 - 答疑平台账号信息"
msg["From"] = from_addr
msg["To"] = cred.email
try:
server.send_message(msg)
console.print(
f" [{i}/{len(credentials)}] [green]已发送[/green] -> {cred.email}"
)
stats["sent"] += 1
except Exception as e:
console.print(
f" [{i}/{len(credentials)}] [red]失败[/red] -> {cred.email}: {e}"
)
stats["failed"] += 1
# 按 batch_size 暂停, 避免触发 SMTP 速率限制
if i % batch_size == 0 and i < len(credentials):
console.print(f" [dim]已发送 {i} 封, 暂停 2 秒...[/dim]")
time.sleep(2)
except Exception as e:
console.print(f"[red]SMTP 连接失败: {e}[/red]")
raise typer.Exit(code=1) from e
console.print(f"\n完成: 发送 {stats['sent']}, 失败 {stats['failed']}")
+3 -49
View File
@@ -12,28 +12,12 @@ from rich.table import Table
from tjhlp.client import GiteaClient, GiteaClientError
from tjhlp.config import get_gitea_config
from tjhlp.models import CredentialRecord, MemberRecord, MemberRole
from tjhlp.models import MemberRecord, MemberRole
app = typer.Typer(no_args_is_help=True)
console = Console()
def _generate_password(length: int = 12) -> str:
"""生成随机密码: 至少包含大小写字母、数字和特殊字符"""
if length < 8:
length = 8
alphabet = string.ascii_letters + string.digits + "!@#$%&*"
while True:
password = "".join(secrets.choice(alphabet) for _ in range(length))
if (
any(c.islower() for c in password)
and any(c.isupper() for c in password)
and any(c.isdigit() for c in password)
and any(c in "!@#$%&*" for c in password)
):
return password
def _read_members_csv(filepath: Path) -> list[MemberRecord]:
"""读取 members CSV 文件"""
records: list[MemberRecord] = []
@@ -48,10 +32,9 @@ def _read_members_csv(filepath: Path) -> list[MemberRecord]:
def create_users(
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"),
output: Path = typer.Option(None, "--output", "-o", help="凭据输出文件路径(默认自动生成)"),
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"),
) -> None:
"""从 CSV 批量创建用户账号, 生成随机密码并输出到凭据文件"""
"""从 CSV 批量创建用户账号(初始密码与用户名相同)"""
if not file.exists():
console.print(f"[red]文件不存在: {file}[/red]")
raise typer.Exit(code=1)
@@ -75,7 +58,6 @@ def create_users(
console.print(table)
return
credentials: list[CredentialRecord] = []
stats = {"created": 0, "skipped": 0, "failed": 0}
with GiteaClient(cfg) as client:
@@ -94,12 +76,10 @@ def create_users(
stats["skipped"] += 1
continue
password = _generate_password(cfg.password_length)
try:
client.create_user(
username=member.username,
password=password,
password=member.username,
email=member.email,
full_name=member.name,
must_change_password=True,
@@ -107,17 +87,6 @@ def create_users(
console.print(f" [green]创建[/green] {member.username}({member.name})")
stats["created"] += 1
credentials.append(
CredentialRecord(
id=member.id,
name=member.name,
role=member.role.value,
username=member.username,
password=password,
email=member.email,
)
)
# 添加到团队
if org:
team = ta_team if member.role == MemberRole.TA else students_team
@@ -131,21 +100,6 @@ def create_users(
console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}")
stats["failed"] += 1
# 写出凭据文件
if credentials:
if output is None:
ts = datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S")
output = Path(f"credentials_{ts}.csv")
with open(output, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(
f,
fieldnames=["id", "name", "role", "username", "password", "email"],
)
writer.writeheader()
for cred in credentials:
writer.writerow(cred.model_dump())
console.print(f"\n凭据已保存到 [bold]{output}[/bold]")
console.print(
f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
)
+1 -26
View File
@@ -20,7 +20,7 @@ settings = Dynaconf(
],
environments=True,
load_dotenv=True,
merge_enabled=True
merge_enabled=True,
)
@@ -55,25 +55,9 @@ class GiteaConfig(BaseModel):
token: SecretStr
email_domain: str = "tongji.edu.cn"
default_org: str = ""
password_length: int = 16
labels: list[LabelDef] = []
class SmtpConfig(BaseModel):
"""SMTP 邮件配置"""
model_config = ConfigDict(
alias_generator=AliasGenerator(validation_alias=str.upper),
populate_by_name=True,
)
host: str
port: int = 465
user: str
password: SecretStr
from_addr: str = ""
class Config(BaseModel):
"""总配置模型"""
@@ -85,7 +69,6 @@ class Config(BaseModel):
)
gitea: GiteaConfig
smtp: SmtpConfig | None = None
def get_config() -> Config:
@@ -96,11 +79,3 @@ def get_config() -> Config:
def get_gitea_config() -> GiteaConfig:
"""从 Dynaconf 加载并校验 Gitea 配置"""
return get_config().gitea
def get_smtp_config() -> SmtpConfig:
"""从 Dynaconf 加载并校验 SMTP 配置"""
cfg = get_config()
if cfg.smtp is None:
raise ValueError("SMTP 配置缺失, 请在 .secrets.toml 中配置")
return cfg.smtp
-11
View File
@@ -34,17 +34,6 @@ class MemberRecord(BaseModel):
return self.id
class CredentialRecord(BaseModel):
"""生成的凭据记录(输出到 credentials CSV)"""
id: str
name: str
role: str
username: str
password: str
email: str
# ---------------------------------------------------------------------------
# Gitea API 响应模型(部分字段)
# ---------------------------------------------------------------------------