Compare commits
35
Commits
| Author | SHA1 | Date | ||
|---|---|---|---|---|
| ||||
|
|
1ff6eb13e6 | |||
|
|
0d77dc3572 | |||
| ||||
|
|
7c66cb931a | |||
|
|
5995efc7a0 | |||
|
|
c26e834982 | |||
|
|
fdf90f4b1d | |||
|
|
9844988cf2 | |||
|
|
d16ed6c1e8 | |||
|
|
edc68744d5 | |||
|
|
7176bea12c | |||
|
|
0ea921186a | |||
|
|
3558247aac | |||
|
|
82c878ce33 | |||
|
|
381b98bf1f | |||
|
|
7361ad157d | |||
|
|
17b6ee35ef | |||
|
|
74204f7bb2 | |||
|
|
645c990778 | |||
| ||||
|
|
1e05b18f0c | |||
|
|
68ef257759 | |||
|
|
c4acf06253 | |||
|
|
38ccc16d7a | |||
|
|
ab49b93c4d | |||
|
|
627d284b02 | |||
|
|
f147f4b248 | |||
|
|
75cc78d5f8 | |||
|
|
51032c44d0 | |||
|
|
2f9528939a | |||
|
|
f982b2e0a6 | |||
|
|
b0bf66e1aa | |||
|
|
b1f4363433 | |||
|
|
57a99ccd23 | |||
|
|
c6bf968178 | |||
|
|
f1c9aca4c7 | |||
|
|
86a934ac87 | |||
No files matched your search
@@ -4,14 +4,17 @@
|
|||||||
|
|
||||||
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
||||||
|
|
||||||
|
**在线演示:** https://lite.forumlify.org
|
||||||
|
|
||||||
## ✨ 特性
|
## ✨ 特性
|
||||||
|
|
||||||
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
||||||
- ⚡️ 轻量快速,无需复杂配置
|
- ⚡️ 轻量快速,无需复杂配置
|
||||||
- 🔐 自带用户认证(JWT)
|
- 🔐 自带用户认证(JWT),改密码后旧令牌立即失效
|
||||||
- 📝 发帖、回复、举报、管理后台
|
- 📝 发帖、回复、举报、私信、管理后台
|
||||||
|
- 📧 邮件支持:后台配置 SMTP,可用于注册邮箱验证与密码找回
|
||||||
|
- 🌍 界面中英文双语,管理后台可配置自定义页面与样式
|
||||||
- 🐳 Docker 一键部署
|
- 🐳 Docker 一键部署
|
||||||
- 🌓 暗色/亮色模式切换
|
|
||||||
|
|
||||||
## 🤔 如何选择版本
|
## 🤔 如何选择版本
|
||||||
|
|
||||||
@@ -38,7 +41,7 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
|
|||||||
|
|
||||||
```
|
```
|
||||||
git clone https://github.com/forumlify/public.git
|
git clone https://github.com/forumlify/public.git
|
||||||
cd forumlify
|
cd public
|
||||||
|
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
|
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
|
||||||
@@ -49,6 +52,10 @@ docker compose up --build -d
|
|||||||
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
|
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
|
||||||
`JWT_SECRET` 会使现有登录令牌失效。
|
`JWT_SECRET` 会使现有登录令牌失效。
|
||||||
|
|
||||||
|
> `git clone` 生成的目录名是 `public`(取自仓库名),不是 `forumlify`。
|
||||||
|
> 若想使用其他目录名,可在 clone 时指定,例如
|
||||||
|
> `git clone https://github.com/forumlify/public.git forumlify`。
|
||||||
|
|
||||||
应用默认运行在 `http://localhost:3000`。
|
应用默认运行在 `http://localhost:3000`。
|
||||||
|
|
||||||
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
|
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
|
||||||
@@ -105,14 +112,33 @@ npm install
|
|||||||
|
|
||||||
2. **准备数据库**
|
2. **准备数据库**
|
||||||
|
|
||||||
|
创建数据库用户与空库即可,表结构交给迁移脚本处理:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';"
|
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '请替换为强密码';"
|
||||||
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
|
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
|
||||||
psql -U forumlify -d forumlify -f schema.sql
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> `schema.sql` 仅作为表结构的参考快照保留,**不要**再用它手工建表。
|
||||||
|
> 请统一使用第 4 步的 `npm run migrate`,它会按顺序执行 `migrations/`
|
||||||
|
> 下的文件并记录版本。手工建表后再跑迁移会导致版本记录与实际结构
|
||||||
|
> 不一致,后续升级容易出错。
|
||||||
|
|
||||||
3. **配置环境变量**
|
3. **配置环境变量**
|
||||||
|
|
||||||
|
复制示例文件并按需修改:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
`migrations/` 与 `server.js` 直接读取进程环境变量,`.env` 不会自动加载。
|
||||||
|
使用 `npm start` 手动启动时,请先导出这些变量:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
set -a && . ./.env && set +a
|
||||||
|
```
|
||||||
|
|
||||||
| 变量 | 默认值 | 说明 |
|
| 变量 | 默认值 | 说明 |
|
||||||
|------|--------|------|
|
|------|--------|------|
|
||||||
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||||
@@ -121,7 +147,7 @@ psql -U forumlify -d forumlify -f schema.sql
|
|||||||
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
||||||
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
||||||
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
|
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
|
||||||
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册时填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
||||||
|
|
||||||
|
|
||||||
4. **执行迁移并启动**
|
4. **执行迁移并启动**
|
||||||
@@ -133,6 +159,15 @@ npm start
|
|||||||
|
|
||||||
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
|
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
|
||||||
|
|
||||||
|
#### 创建第一个管理员
|
||||||
|
|
||||||
|
站点默认没有任何管理员。首次部署时在 `.env` 中设置一个强随机
|
||||||
|
`ADMIN_BOOTSTRAP_TOKEN`,然后在注册页面的「管理员初始化令牌」一栏填入
|
||||||
|
相同的值完成注册,该账号即成为管理员。
|
||||||
|
|
||||||
|
管理员只能这样创建:普通注册一律是普通用户,且系统存在管理员后,
|
||||||
|
引导令牌不再生效。初始化完成后请从 `.env` 中删除该变量并重启服务。
|
||||||
|
|
||||||
#### 前端配置
|
#### 前端配置
|
||||||
|
|
||||||
前端页面为 `index.html`,相关行为可在 `config.js` 中调整:
|
前端页面为 `index.html`,相关行为可在 `config.js` 中调整:
|
||||||
@@ -151,28 +186,264 @@ npm start
|
|||||||
mkdir -p uploads && chmod 755 uploads
|
mkdir -p uploads && chmod 755 uploads
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### 反向代理与 HTTPS
|
||||||
|
|
||||||
|
生产环境建议让 Nginx 终止 TLS 并反代到本机的 3000 端口。要点如下:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name lite.example.org;
|
||||||
|
|
||||||
|
ssl_certificate /etc/nginx/ssl/lite.example.org.fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/nginx/ssl/lite.example.org.key;
|
||||||
|
|
||||||
|
# 保留 ACME 挑战路径,否则证书续期会失败
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/acme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:3000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
配套设置 `.env` 中的 `TRUST_PROXY=true`,否则限流会把所有用户识别为
|
||||||
|
同一个来源 IP。应用记录审计日志时也依赖该设置取到真实客户端地址。
|
||||||
|
|
||||||
|
两个容易踩的坑:
|
||||||
|
|
||||||
|
- **80 端口若已存在其他站点的 `default_server`**,它会接管所有未显式
|
||||||
|
匹配的 Host,导致本域名的 ACME 挑战请求被 301 跳走、证书签发失败。
|
||||||
|
必须为本域名单独写一个 `server_name` 的 80 端口块。
|
||||||
|
- **ACME 挑战路径要放在 `return 301` 之前**,否则同样会被重定向。
|
||||||
|
|
||||||
|
### 邮件(SMTP)
|
||||||
|
|
||||||
|
邮件功能**默认关闭**,全部在管理后台配置,无需改环境变量或重启服务。
|
||||||
|
入口:登录管理员账号 → 右上角头像 → **管理后台** → **邮件设置**。
|
||||||
|
|
||||||
|
> 配置保存在数据库的 `settings` 表中,因此在 Docker 部署下也会随
|
||||||
|
> `db_data` 卷一起持久化,容器重建不会丢失,也不需要给 Compose 增加
|
||||||
|
> 任何环境变量。
|
||||||
|
|
||||||
|
配置项:
|
||||||
|
|
||||||
|
| 字段 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| 启用邮件发送 | 总开关,关闭时所有邮件功能不可用 |
|
||||||
|
| SMTP 服务器 | 如 `smtp.qq.com`、`smtp.gmail.com` |
|
||||||
|
| 端口 | 587(STARTTLS)或 465(SSL/TLS) |
|
||||||
|
| 加密方式 | 需与端口匹配:**587 选 STARTTLS,465 选 SSL/TLS** |
|
||||||
|
| 用户名 | 通常为完整邮箱地址 |
|
||||||
|
| 密码 / 授权码 | 见下方说明 |
|
||||||
|
| 发件人名称 | 显示在收件人邮箱里的发件人名字 |
|
||||||
|
| 发件人邮箱 | 必填,建议与用户名一致,否则易被判定为伪造发件人 |
|
||||||
|
|
||||||
|
填写后点击**发送测试邮件**验证连通性,默认发到当前管理员的邮箱。
|
||||||
|
测试通过即表示配置可用。
|
||||||
|
|
||||||
|
#### 关于「授权码」
|
||||||
|
|
||||||
|
**QQ 邮箱、163、Gmail 等服务商不能用登录密码发信**,必须先生成专用
|
||||||
|
授权码:
|
||||||
|
|
||||||
|
- **QQ 邮箱**:设置 → 账户 → 开启 SMTP 服务 → 生成授权码
|
||||||
|
- **163 邮箱**:设置 → POP3/SMTP/IMAP → 开启服务 → 获取授权码
|
||||||
|
- **Gmail**:需开启两步验证后创建「应用专用密码」
|
||||||
|
|
||||||
|
把授权码填进「密码 / 授权码」一栏即可。
|
||||||
|
|
||||||
|
#### 使用 Resend
|
||||||
|
|
||||||
|
[Resend](https://resend.com) 提供 SMTP 接口,按其官方参数填写即可:
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| SMTP 服务器 | `smtp.resend.com` |
|
||||||
|
| 端口 | `465`(推荐)或 `587` |
|
||||||
|
| 加密方式 | 465 选 **SSL/TLS**;587 选 STARTTLS |
|
||||||
|
| 用户名 | `resend` ← **固定值,不是邮箱地址** |
|
||||||
|
| 密码 / 授权码 | 你的 **API Key**(`re_` 开头) |
|
||||||
|
| 发件人邮箱 | 已验证域名下的地址,如 `noreply@你的域名` |
|
||||||
|
|
||||||
|
使用前需在 Resend 控制台完成两件事:**创建 API Key**,以及
|
||||||
|
**添加并验证发信域名**(配置 SPF / DKIM 记录)。未验证域名时
|
||||||
|
只能发往自己的注册邮箱,无法发给其他收件人。
|
||||||
|
|
||||||
|
> 用户名填成自己的邮箱地址是常见错误——Resend 要求固定填 `resend`。
|
||||||
|
|
||||||
|
##### Resend 的收件人限制
|
||||||
|
|
||||||
|
Resend **禁止向 `example.com`、`test.com` 等保留/测试域名发信**,
|
||||||
|
会直接返回 `550 Invalid to field`。这是服务商的反滥用策略,不是本站
|
||||||
|
的限制。
|
||||||
|
|
||||||
|
因此**不要用测试域名验证邮件功能**——测试时请使用真实可收信的邮箱。
|
||||||
|
本站会把该错误翻译成中文提示。
|
||||||
|
|
||||||
|
若已启用注册邮箱验证,而用户恰好使用了这类邮箱注册,会看到
|
||||||
|
「收件人邮箱被邮件服务商拒绝」的提示,属预期行为。
|
||||||
|
|
||||||
|
#### 使用其他服务商
|
||||||
|
|
||||||
|
常见服务商的 SMTP 参数:
|
||||||
|
|
||||||
|
| 服务商 | 服务器 | 端口 | 用户名 | 密码 |
|
||||||
|
|--------|--------|------|--------|------|
|
||||||
|
| QQ 邮箱 | `smtp.qq.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||||
|
| 163 邮箱 | `smtp.163.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||||
|
| Gmail | `smtp.gmail.com` | 465 / 587 | 完整邮箱 | 应用专用密码 |
|
||||||
|
| Resend | `smtp.resend.com` | 465 / 587 | `resend` | API Key |
|
||||||
|
| 阿里云邮件推送 | `smtpdm.aliyun.com` | 465 / 80 | 发信地址 | 设置的密码 |
|
||||||
|
|
||||||
|
#### 关于「允许自签证书」
|
||||||
|
|
||||||
|
默认开启证书校验。如果你使用的是**自建邮件服务器且用自签证书**,
|
||||||
|
连接会因证书不受信任而失败,此时才需要打开这个开关。
|
||||||
|
|
||||||
|
对 Resend、QQ、Gmail 等使用可信证书的服务商,**保持关闭**。关闭校验
|
||||||
|
会让连接暴露在中间人攻击下。
|
||||||
|
|
||||||
|
#### 密码的存储与显示
|
||||||
|
|
||||||
|
SMTP 密码**只写不读**:保存后任何接口都不会返回明文,界面只显示
|
||||||
|
「已保存密码,留空则不修改」。因此:
|
||||||
|
|
||||||
|
- 想改其他字段时,**密码栏留空即可**,原密码保持不变
|
||||||
|
- 需要更换密码时才填写新值
|
||||||
|
- 「清除密码」按钮用于彻底移除已保存的密码
|
||||||
|
|
||||||
|
#### 邮件用在哪里
|
||||||
|
|
||||||
|
配置完成并发送测试邮件成功后,可以开启 **要求注册时验证邮箱**:
|
||||||
|
|
||||||
|
- **注册邮箱验证**:新用户注册时必须填写邮箱收到的 6 位验证码。
|
||||||
|
验证码 10 分钟有效,连续输错 5 次即作废,且只能使用一次。
|
||||||
|
该字段仅在开启此选项时才出现在注册框里。
|
||||||
|
- **密码找回**:登录页的「忘记密码」支持通过邮箱验证码重置密码,
|
||||||
|
与原有的恢复码机制并行,两种方式都可用。
|
||||||
|
|
||||||
|
> 未完成 SMTP 配置时**无法开启**注册邮箱验证——这是有意为之,
|
||||||
|
> 避免开启后所有人都注册不了。
|
||||||
|
|
||||||
|
#### 常见配置问题
|
||||||
|
|
||||||
|
| 现象 | 原因 |
|
||||||
|
|------|------|
|
||||||
|
| 认证失败 | 用了登录密码而非授权码;或用 Resend 时用户名没填 `resend` |
|
||||||
|
| 连接超时 | 端口被防火墙拦截,**或加密方式与端口不匹配**(465 必须配 SSL/TLS) |
|
||||||
|
| 套接字错误 | 同上,端口与加密方式不匹配;也可能是证书校验未通过 |
|
||||||
|
| 发件人被拒 | 发件人邮箱不属于已验证的域名,或与服务商要求不符 |
|
||||||
|
| 域名解析失败 | SMTP 服务器地址拼写错误 |
|
||||||
|
| 证书校验失败 | 自建服务器用了自签证书,需打开「允许自签证书」 |
|
||||||
|
|
||||||
|
多数云服务商默认封禁 25 端口,建议使用 465 或 587。
|
||||||
|
|
||||||
|
> 排错时最有效的两步:先在后台点**发送测试邮件**看具体报错,
|
||||||
|
> 再对照上表定位。中间的错误提示会直接给出去改哪个字段。
|
||||||
|
|
||||||
## 📁 项目结构
|
## 📁 项目结构
|
||||||
|
|
||||||
```
|
```
|
||||||
forumlify/
|
public/
|
||||||
├── index.html # 前端页面
|
├── index.html # 前端页面
|
||||||
├── style.css # 全局样式
|
├── style.css # 全局样式
|
||||||
├── Dockerfile # Docker 镜像构建文件
|
├── config.js # 前端配置(同时也是服务端配置入口)
|
||||||
├── package-lock.json # 依赖锁定文件
|
|
||||||
├── server.js # 后端服务(Express)
|
├── server.js # 后端服务(Express)
|
||||||
├── js/ # 前端 JS 模块
|
├── lib/
|
||||||
│ ├── app.js
|
│ └── mailer.js # SMTP 发信封装(配置读取、发送、错误翻译)
|
||||||
│ ├── admin.js
|
├── Dockerfile # Docker 镜像构建文件
|
||||||
│ ├── api.js
|
├── docker-compose.yml # Docker 编排
|
||||||
│ ├── auth.js
|
├── package-lock.json # 依赖锁定文件
|
||||||
│ ├── feed.js
|
├── migrations/ # 数据库迁移(按文件名顺序执行,请勿手工修改已应用的版本)
|
||||||
│ ├── post.js
|
│ ├── 001_initial.sql
|
||||||
│ └── user.js
|
│ ├── 002_restore_auth_and_audit_columns.sql
|
||||||
├── schema.sql # 数据库表结构
|
│ └── 003_email_verification.sql
|
||||||
├── config.js # 配置文件
|
├── schema.sql # 表结构参考快照(仅供阅读,请勿用于建表)
|
||||||
└── docker-compose.yml # Docker 编排
|
├── scripts/
|
||||||
|
│ ├── migrate.js # 迁移执行器
|
||||||
|
│ ├── docker-entrypoint.sh
|
||||||
|
│ └── healthcheck.js
|
||||||
|
├── test/ # 测试(node --test)
|
||||||
|
│ ├── app.test.js # 接口与安全头
|
||||||
|
│ ├── bootstrap-ui.test.js # 管理员引导令牌的显示条件
|
||||||
|
│ ├── i18n-coverage.test.js # 界面文案翻译覆盖率
|
||||||
|
│ ├── migration-schema.test.js # 迁移必须覆盖服务端依赖的列
|
||||||
|
│ └── schema-parity.test.js # schema.sql 与 migrations 的结构一致性
|
||||||
|
└── js/ # 前端 JS 模块
|
||||||
|
├── app.js # 主入口、路由、Toast、确认框
|
||||||
|
├── admin.js # 管理后台各标签页
|
||||||
|
├── api.js # 接口封装
|
||||||
|
├── auth.js # 登录、注册、退出
|
||||||
|
├── captcha.js # 人机验证
|
||||||
|
├── feed.js # 帖子列表
|
||||||
|
├── i18n.js # 中英文词典与外挂翻译
|
||||||
|
├── icons.js # SVG 图标
|
||||||
|
├── post.js # 帖子详情与回复
|
||||||
|
├── security.js # 转义与安全渲染
|
||||||
|
├── theme.js # 亮色/暗色切换
|
||||||
|
└── user.js # 用户主页
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## ❓ 常见问题
|
||||||
|
|
||||||
|
**升级代码后,登录之后的接口全部返回 500?**
|
||||||
|
|
||||||
|
说明数据库缺少 `users.token_version` 或 `event_logs` 的审计字段。执行
|
||||||
|
`npm run migrate` 应用 `migrations/` 中的修复迁移即可,无需重建数据库。
|
||||||
|
若该库曾经手工执行过 `schema.sql`,迁移记录可能与实际结构不一致,可先
|
||||||
|
检查 `SELECT * FROM schema_migrations;`。
|
||||||
|
|
||||||
|
**忘记了管理员密码?**
|
||||||
|
|
||||||
|
两种方式:若已配置邮件,在登录页的「忘记密码」用邮箱验证码重置;
|
||||||
|
否则使用注册后在设置页生成的恢复码重置。恢复码建议生成后立即离线保存。
|
||||||
|
|
||||||
|
**修改密码或邮箱后被登出?**
|
||||||
|
|
||||||
|
这两个操作会递增 `users.token_version` 使所有已签发的令牌失效,属于预期
|
||||||
|
行为;服务端会随响应补发一个新令牌,前端会自动保存并保持在登录状态。
|
||||||
|
若仍被登出,请强制刷新页面(Ctrl+F5)以载入最新的前端脚本。
|
||||||
|
|
||||||
|
**注册框里看不到邮箱验证码输入框?**
|
||||||
|
|
||||||
|
这是正常的。该字段仅在管理后台开启了「要求注册时验证邮箱」、
|
||||||
|
且 SMTP 配置完整时才显示。未配置邮件时注册流程与以往一致。
|
||||||
|
|
||||||
|
**开启了邮箱验证,但收不到验证码?**
|
||||||
|
|
||||||
|
先在后台点「发送测试邮件」确认 SMTP 可用。若测试邮件能收到而验证码
|
||||||
|
收不到,检查是否被投进了垃圾箱;若用的是自建发信域名,还需配置 SPF
|
||||||
|
与 DKIM 记录,否则容易进垃圾箱或被直接拒收。
|
||||||
|
|
||||||
|
**用 Resend 发送失败?**
|
||||||
|
|
||||||
|
按顺序检查三项:用户名必须是 `resend`(不是你的邮箱)、密码必须是
|
||||||
|
`re_` 开头的 API Key、发件人邮箱必须属于已在 Resend 验证过的域名。
|
||||||
|
若尚未验证域名,Resend 只允许发往账号注册邮箱,发给其他地址会被拒。
|
||||||
|
|
||||||
|
**怎么确认 SMTP 是通的?**
|
||||||
|
|
||||||
|
后台「发送测试邮件」默认发到当前管理员的邮箱。收到即表示配置可用,
|
||||||
|
不必开启注册验证去试探。
|
||||||
|
|
||||||
|
**邮件相关接口返回 429?**
|
||||||
|
|
||||||
|
发送验证码与找回密码的接口有独立限流(15 分钟 5 次),用于防止被当作
|
||||||
|
垃圾邮件发射器。稍后再试即可。
|
||||||
|
|
||||||
|
**改动 SMTP 配置后没有生效?**
|
||||||
|
|
||||||
|
配置保存在数据库中,保存即时生效,无需重启。若填了新的密码但仍是旧
|
||||||
|
行为,确认密码栏确实填入了新值——留空表示保持原密码不变。
|
||||||
|
|
||||||
## 📝 License
|
## 📝 License
|
||||||
|
|
||||||
MIT
|
MIT
|
||||||
|
|||||||
+109
-25
@@ -101,13 +101,57 @@
|
|||||||
<button class="tab active" data-sort="latest">最新发布</button>
|
<button class="tab active" data-sort="latest">最新发布</button>
|
||||||
<button class="tab" data-sort="hot">最新回复</button>
|
<button class="tab" data-sort="hot">最新回复</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="feed-search">
|
||||||
|
<!-- 防止密码管理器误填:Chrome 等对 autocomplete="off" 常忽略,
|
||||||
|
因此叠加多重标识——语义化的 role/type、不易被判定为账号
|
||||||
|
字段的 name,以及 1Password / LastPass 识别的 data 属性。
|
||||||
|
同时把三个含密码的模态框改成真正的 <form>,让密码管理器
|
||||||
|
有明确的表单边界,不再靠启发式猜测波及搜索框。 -->
|
||||||
|
<input type="search" id="postSearchInput" name="post-search-query"
|
||||||
|
placeholder="搜索帖子…" autocomplete="off" autocorrect="off"
|
||||||
|
autocapitalize="off" spellcheck="false"
|
||||||
|
role="searchbox" aria-label="搜索帖子"
|
||||||
|
data-form-type="other" data-1p-ignore data-lpignore="true" />
|
||||||
|
<button id="postSearchClear" class="feed-search-clear" type="button" title="清除搜索" style="display:none;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
<button id="fab" class="btn-primary fab-btn">
|
<button id="fab" class="btn-primary fab-btn">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||||
发布新帖
|
发布新帖
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="postList">
|
<div id="postList">
|
||||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
<!-- 骨架屏直接写在标记里,保证首帧即可见。
|
||||||
|
若留空或写「加载中...」文字,会先闪一帧空白/文字再被
|
||||||
|
JS 替换成骨架,实测有 18ms 的可见闪动。 -->
|
||||||
|
<div class="skeleton-card">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line skeleton-title w-60"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-80"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-card">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line skeleton-title w-60"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-80"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-card">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line skeleton-title w-60"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-80"></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
@@ -129,7 +173,7 @@
|
|||||||
<!-- 设置页面 -->
|
<!-- 设置页面 -->
|
||||||
<div id="pageSettings" class="page-slide">
|
<div id="pageSettings" class="page-slide">
|
||||||
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
||||||
<button class="back-btn" onclick="switchPage('feed')">
|
<button class="back-btn">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||||
返回
|
返回
|
||||||
</button>
|
</button>
|
||||||
@@ -177,7 +221,7 @@
|
|||||||
<!-- 管理后台 -->
|
<!-- 管理后台 -->
|
||||||
<div id="pageAdmin" class="page-slide">
|
<div id="pageAdmin" class="page-slide">
|
||||||
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
||||||
<button class="back-btn" onclick="switchPage('feed')">
|
<button class="back-btn">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||||
返回
|
返回
|
||||||
</button>
|
</button>
|
||||||
@@ -227,6 +271,12 @@
|
|||||||
</span>
|
</span>
|
||||||
论坛设置
|
论坛设置
|
||||||
</a>
|
</a>
|
||||||
|
<a href="#" class="admin-nav-item" data-tab="smtp">
|
||||||
|
<span class="nav-icon">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
|
||||||
|
</span>
|
||||||
|
邮件设置
|
||||||
|
</a>
|
||||||
<a href="#" class="admin-nav-item" data-tab="custom">
|
<a href="#" class="admin-nav-item" data-tab="custom">
|
||||||
<span class="nav-icon">
|
<span class="nav-icon">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
||||||
@@ -272,7 +322,7 @@
|
|||||||
<!-- 帖子详情页 -->
|
<!-- 帖子详情页 -->
|
||||||
<div id="pagePost" class="page-slide">
|
<div id="pagePost" class="page-slide">
|
||||||
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
<div class="page-header" style="max-width:1200px;margin:0 auto;width:100%;">
|
||||||
<button class="back-btn" onclick="switchPage('feed')">
|
<button class="back-btn">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||||
返回
|
返回
|
||||||
</button>
|
</button>
|
||||||
@@ -324,7 +374,7 @@
|
|||||||
<!-- 用户主页 -->
|
<!-- 用户主页 -->
|
||||||
<div id="pageUser" class="page-slide">
|
<div id="pageUser" class="page-slide">
|
||||||
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
|
<div class="page-header" style="max-width:700px;margin:0 auto;width:100%;">
|
||||||
<button class="back-btn" onclick="switchPage('feed')">
|
<button class="back-btn">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||||
返回
|
返回
|
||||||
</button>
|
</button>
|
||||||
@@ -343,12 +393,18 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||||
</span>
|
</span>
|
||||||
<h2 style="margin-bottom:16px;">登录</h2>
|
<h2 style="margin-bottom:16px;">登录</h2>
|
||||||
<input type="email" id="loginEmail" placeholder="邮箱" />
|
<!-- 用真正的 form 包裹:页面此前完全没有 form 标签,密码管理器
|
||||||
<input type="password" id="loginPassword" placeholder="密码" />
|
找不到表单边界,只能靠启发式猜测,会把页面上的其他文本框
|
||||||
<div style="text-align:center;margin-top:8px;">
|
(如首页搜索框)也当作账号字段填入。
|
||||||
<a href="#" id="forgotPasswordLink" style="color:var(--primary);font-size:13px;text-decoration:none;">忘记密码?</a>
|
autocomplete 采用标准值,帮助密码管理器准确定位。 -->
|
||||||
</div>
|
<form id="loginForm" autocomplete="on">
|
||||||
<button id="loginSubmit" class="btn-primary" style="width:100%;margin-top:8px;">登录</button>
|
<input type="email" id="loginEmail" name="email" placeholder="邮箱" autocomplete="username" />
|
||||||
|
<input type="password" id="loginPassword" name="password" placeholder="密码" autocomplete="current-password" />
|
||||||
|
<div style="text-align:center;margin-top:8px;">
|
||||||
|
<a href="#" id="forgotPasswordLink" style="color:var(--primary);font-size:13px;text-decoration:none;">忘记密码?</a>
|
||||||
|
</div>
|
||||||
|
<button type="submit" id="loginSubmit" class="btn-primary" style="width:100%;margin-top:8px;">登录</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -359,15 +415,21 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||||
</span>
|
</span>
|
||||||
<h2 style="margin-bottom:16px;">注册</h2>
|
<h2 style="margin-bottom:16px;">注册</h2>
|
||||||
<input type="text" id="regUsername" placeholder="用户名" />
|
<form id="registerForm" autocomplete="on">
|
||||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
<input type="text" id="regUsername" name="username" placeholder="用户名" autocomplete="username" />
|
||||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
<input type="email" id="regEmail" name="email" placeholder="邮箱" autocomplete="email" />
|
||||||
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌(仅首次部署,可选)" autocomplete="off" />
|
<input type="password" id="regPassword" name="password" placeholder="密码(至少6位)" autocomplete="new-password" />
|
||||||
<div class="captcha-row">
|
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌" autocomplete="off" style="display:none;" />
|
||||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
<div id="regEmailCodeRow" class="email-code-row">
|
||||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
<input type="text" id="regEmailCode" placeholder="邮箱验证码" autocomplete="one-time-code" />
|
||||||
</div>
|
<button type="button" id="regSendCodeBtn" class="btn-secondary">获取验证码</button>
|
||||||
<button id="registerSubmit" class="btn-primary" style="width:100%;">注册</button>
|
</div>
|
||||||
|
<div class="captcha-row">
|
||||||
|
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||||
|
<input type="text" id="regCaptchaInput" placeholder="答案" autocomplete="off" style="width:80px;" />
|
||||||
|
</div>
|
||||||
|
<button type="submit" id="registerSubmit" class="btn-primary" style="width:100%;">注册</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -401,11 +463,13 @@
|
|||||||
</span>
|
</span>
|
||||||
<h2 style="margin-bottom:16px;">🔑 重置密码</h2>
|
<h2 style="margin-bottom:16px;">🔑 重置密码</h2>
|
||||||
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">输入你的邮箱和一个未使用的恢复码</p>
|
<p style="font-size:14px;color:var(--text-secondary);margin-bottom:16px;">输入你的邮箱和一个未使用的恢复码</p>
|
||||||
<input type="email" id="resetEmail" placeholder="邮箱" />
|
<form id="forgotPasswordForm" autocomplete="on">
|
||||||
<input type="text" id="resetRecoveryCode" placeholder="恢复码(格式:ABCD-1234-EFGH-5678)" style="font-family:monospace;letter-spacing:0.5px;" />
|
<input type="email" id="resetEmail" name="email" placeholder="邮箱" autocomplete="email" />
|
||||||
<input type="password" id="resetNewPassword" placeholder="新密码(至少6位)" />
|
<input type="text" id="resetRecoveryCode" placeholder="恢复码(格式:ABCD-1234-EFGH-5678)" autocomplete="off" style="font-family:monospace;letter-spacing:0.5px;" />
|
||||||
<button id="resetPasswordSubmit" class="btn-primary" style="width:100%;">重置密码</button>
|
<input type="password" id="resetNewPassword" name="new-password" placeholder="新密码(至少6位)" autocomplete="new-password" />
|
||||||
<div id="resetStatus" style="font-size:14px;margin-top:8px;text-align:center;"></div>
|
<button type="submit" id="resetPasswordSubmit" class="btn-primary" style="width:100%;">重置密码</button>
|
||||||
|
<div id="resetStatus" style="font-size:14px;margin-top:8px;text-align:center;"></div>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -416,6 +480,23 @@
|
|||||||
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
|
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
|
||||||
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">×</span>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 用户搜索:此前只能从对方主页点「私信」才能发起会话,
|
||||||
|
这里提供按用户名搜索并直接开聊的入口 -->
|
||||||
|
<div class="dm-search-wrap">
|
||||||
|
<div class="dm-search">
|
||||||
|
<input type="search" id="dmUserSearchInput" name="dm-user-search"
|
||||||
|
placeholder="搜索用户名开始私信…" autocomplete="off"
|
||||||
|
role="searchbox" aria-label="搜索用户"
|
||||||
|
data-form-type="other" data-1p-ignore data-lpignore="true" />
|
||||||
|
<button type="button" id="dmUserSearchClear" class="dm-search-clear" title="清除搜索" style="display:none;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="dm-view-switch">
|
||||||
|
<button type="button" id="dmTabConversations" class="active">会话</button>
|
||||||
|
<button type="button" id="dmTabBlocked">已屏蔽</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
|
||||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -435,6 +516,8 @@
|
|||||||
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
|
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
|
||||||
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 对方回复前的发送条数提示,由 JS 控制显示 -->
|
||||||
|
<div id="chatLimitNote" class="dm-limit-note" style="display:none;"></div>
|
||||||
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
|
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
|
||||||
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
|
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
|
||||||
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
|
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>
|
||||||
@@ -449,6 +532,7 @@
|
|||||||
<script src="js/icons.js"></script>
|
<script src="js/icons.js"></script>
|
||||||
<script src="js/i18n.js"></script>
|
<script src="js/i18n.js"></script>
|
||||||
<script src="js/security.js"></script>
|
<script src="js/security.js"></script>
|
||||||
|
<script src="js/skeleton.js"></script>
|
||||||
<script src="js/api.js"></script>
|
<script src="js/api.js"></script>
|
||||||
<script src="js/theme.js"></script>
|
<script src="js/theme.js"></script>
|
||||||
<script src="js/captcha.js"></script>
|
<script src="js/captcha.js"></script>
|
||||||
|
|||||||
+238
-30
@@ -42,15 +42,20 @@ function renderAdminReports() {
|
|||||||
});
|
});
|
||||||
container.innerHTML = sanitizeHTML(html);
|
container.innerHTML = sanitizeHTML(html);
|
||||||
container.querySelectorAll('[data-action]').forEach(btn => {
|
container.querySelectorAll('[data-action]').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', async function() {
|
||||||
const id = this.dataset.reportid;
|
const id = this.dataset.reportid;
|
||||||
const action = this.dataset.action;
|
const action = this.dataset.action;
|
||||||
const status = action === 'approve' ? 'approved' : 'rejected';
|
const status = action === 'approve' ? 'approved' : 'rejected';
|
||||||
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
|
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
|
||||||
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
|
if (action === 'approve') {
|
||||||
|
const ok = await showConfirm('确定要删除该帖子并标记举报为已处理吗?', {
|
||||||
|
title: '删除帖子', confirmText: '删除', danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
}
|
||||||
API.updateReport(id, status, note).then(() => {
|
API.updateReport(id, status, note).then(() => {
|
||||||
renderAdminReports();
|
renderAdminReports();
|
||||||
}).catch(err => alert('操作失败:' + err.message));
|
}).catch(err => showToast('操作失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
@@ -68,7 +73,7 @@ let usersSearchKeyword = '';
|
|||||||
|
|
||||||
function renderAdminUsers(page = 1, search = '') {
|
function renderAdminUsers(page = 1, search = '') {
|
||||||
const container = document.getElementById('adminContent');
|
const container = document.getElementById('adminContent');
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
container.innerHTML = Skeleton.tableRows(6);
|
||||||
|
|
||||||
currentUsersPage = page;
|
currentUsersPage = page;
|
||||||
usersSearchKeyword = search;
|
usersSearchKeyword = search;
|
||||||
@@ -201,14 +206,19 @@ function renderAdminUsers(page = 1, search = '') {
|
|||||||
|
|
||||||
// 绑定角色切换事件
|
// 绑定角色切换事件
|
||||||
container.querySelectorAll('[data-role]').forEach(btn => {
|
container.querySelectorAll('[data-role]').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', async function() {
|
||||||
const userId = this.dataset.userid;
|
const userId = this.dataset.userid;
|
||||||
const role = this.dataset.role;
|
const role = this.dataset.role;
|
||||||
const roleName = role === 'admin' ? '管理员' : '普通用户';
|
const roleName = role === 'admin' ? '管理员' : '普通用户';
|
||||||
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
|
const ok = await showConfirm(`确定要将该用户设为「${roleName}」吗?`, {
|
||||||
|
title: '修改用户角色',
|
||||||
|
confirmText: '确定',
|
||||||
|
danger: role === 'admin',
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
API.updateUserRole(userId, role).then(() => {
|
API.updateUserRole(userId, role).then(() => {
|
||||||
renderAdminUsers(currentUsersPage, usersSearchKeyword);
|
renderAdminUsers(currentUsersPage, usersSearchKeyword);
|
||||||
}).catch(err => alert('操作失败:' + err.message));
|
}).catch(err => showToast('操作失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -252,8 +262,8 @@ function renderAdminUsers(page = 1, search = '') {
|
|||||||
|
|
||||||
function renderAdminLogs(page = 1) {
|
function renderAdminLogs(page = 1) {
|
||||||
const container = document.getElementById('adminContent');
|
const container = document.getElementById('adminContent');
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:20px 0;">加载中...</div>';
|
container.innerHTML = Skeleton.tableRows(6);
|
||||||
|
|
||||||
API.getEventLogs(page, 20).then(result => {
|
API.getEventLogs(page, 20).then(result => {
|
||||||
const logs = result.data || [];
|
const logs = result.data || [];
|
||||||
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
|
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
|
||||||
@@ -387,11 +397,14 @@ function renderAdminLinks() {
|
|||||||
});
|
});
|
||||||
ul.innerHTML = sanitizeHTML(html);
|
ul.innerHTML = sanitizeHTML(html);
|
||||||
ul.querySelectorAll('[data-linkid]').forEach(btn => {
|
ul.querySelectorAll('[data-linkid]').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', async function() {
|
||||||
if (!confirm('确定删除该链接吗?')) return;
|
const ok = await showConfirm('确定删除该链接吗?', {
|
||||||
|
title: '删除友链', confirmText: '删除', danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
API.deleteLink(this.dataset.linkid).then(() => {
|
API.deleteLink(this.dataset.linkid).then(() => {
|
||||||
loadLinks();
|
loadLinks();
|
||||||
}).catch(err => alert('删除失败:' + err.message));
|
}).catch(err => showToast('删除失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
@@ -400,12 +413,12 @@ function renderAdminLinks() {
|
|||||||
document.getElementById('addLinkBtn').addEventListener('click', function() {
|
document.getElementById('addLinkBtn').addEventListener('click', function() {
|
||||||
const title = document.getElementById('newLinkTitle').value.trim();
|
const title = document.getElementById('newLinkTitle').value.trim();
|
||||||
const url = document.getElementById('newLinkUrl').value.trim();
|
const url = document.getElementById('newLinkUrl').value.trim();
|
||||||
if (!title || !url) { alert('请填写完整信息'); return; }
|
if (!title || !url) { showToast('请填写完整信息', 'warning'); return; }
|
||||||
API.addLink(title, url).then(() => {
|
API.addLink(title, url).then(() => {
|
||||||
document.getElementById('newLinkTitle').value = '';
|
document.getElementById('newLinkTitle').value = '';
|
||||||
document.getElementById('newLinkUrl').value = '';
|
document.getElementById('newLinkUrl').value = '';
|
||||||
loadLinks();
|
loadLinks();
|
||||||
}).catch(err => alert('添加失败:' + err.message));
|
}).catch(err => showToast('添加失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,11 +431,11 @@ function renderAdminSettings() {
|
|||||||
container.innerHTML = `
|
container.innerHTML = `
|
||||||
<h3 style="margin-bottom:16px;text-align:center;">${getIcon('settings')} 论坛名称</h3>
|
<h3 style="margin-bottom:16px;text-align:center;">${getIcon('settings')} 论坛名称</h3>
|
||||||
|
|
||||||
<div style="max-width:400px;margin:0 auto;width:100%;">
|
<div class="forum-name-form">
|
||||||
<label style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;">论坛名称</label>
|
<label for="settingsForumName" style="font-weight:600;font-size:14px;display:block;margin-bottom:6px;width:100%;">论坛名称</label>
|
||||||
<input type="text" id="settingsForumName" style="width:100%;padding:10px 14px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:15px;margin-bottom:12px;font-family:inherit;background:var(--bg);color:var(--text);" />
|
<input type="text" id="settingsForumName" placeholder="论坛名称" />
|
||||||
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
|
<button id="settingsForumSave" class="btn-primary" style="padding:10px 24px;">保存</button>
|
||||||
<span id="settingsResult" style="margin-left:12px;font-size:14px;"></span>
|
<span id="settingsResult" style="font-size:14px;"></span>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@@ -432,22 +445,208 @@ function renderAdminSettings() {
|
|||||||
|
|
||||||
document.getElementById('settingsForumSave').addEventListener('click', async () => {
|
document.getElementById('settingsForumSave').addEventListener('click', async () => {
|
||||||
const name = document.getElementById('settingsForumName').value.trim();
|
const name = document.getElementById('settingsForumName').value.trim();
|
||||||
if (!name) { alert('请输入论坛名称'); return; }
|
if (!name) { showToast('请输入论坛名称', 'warning'); return; }
|
||||||
try {
|
try {
|
||||||
await API.updateSettings(name);
|
await API.updateSettings(name);
|
||||||
document.getElementById('settingsResult').textContent = `${getIcon('success')} 保存成功!`;
|
document.getElementById('settingsResult').innerHTML = `${getIcon('success')} 保存成功!`;
|
||||||
document.getElementById('settingsResult').style.color = '#22c55e';
|
document.getElementById('settingsResult').style.color = '#22c55e';
|
||||||
document.getElementById('forumName').textContent = name;
|
document.getElementById('forumName').textContent = name;
|
||||||
document.title = name;
|
document.title = name;
|
||||||
const titleEl = document.getElementById('pageTitle');
|
const titleEl = document.getElementById('pageTitle');
|
||||||
if (titleEl) titleEl.textContent = name;
|
if (titleEl) titleEl.textContent = name;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
document.getElementById('settingsResult').textContent = `${getIcon('error')} 保存失败`;
|
document.getElementById('settingsResult').innerHTML = `${getIcon('error')} 保存失败`;
|
||||||
document.getElementById('settingsResult').style.color = '#ef4444';
|
document.getElementById('settingsResult').style.color = '#ef4444';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 📧 邮件设置(SMTP)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
function renderAdminSmtp() {
|
||||||
|
const container = document.getElementById('adminContent');
|
||||||
|
container.innerHTML = `
|
||||||
|
<h3 style="margin-bottom:6px;text-align:center;">${getIcon('message')} 邮件设置</h3>
|
||||||
|
<p style="text-align:center;color:var(--text-secondary);font-size:13px;margin-bottom:20px;">
|
||||||
|
配置后可用于注册邮箱验证与密码找回。密码只写不读,保存后不会回显。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="smtp-form">
|
||||||
|
<div id="smtpStatus" style="margin-bottom:16px;padding:10px 14px;border-radius:var(--radius-sm);font-size:13px;"></div>
|
||||||
|
|
||||||
|
<label class="smtp-check">
|
||||||
|
<input type="checkbox" id="smtpEnabled" />
|
||||||
|
启用邮件发送
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label for="smtpHost">SMTP 服务器</label>
|
||||||
|
<input type="text" id="smtpHost" placeholder="smtp.example.com" autocomplete="off" />
|
||||||
|
<div class="smtp-hint">
|
||||||
|
Resend 填 <code>smtp.resend.com</code>,端口 465、加密选 SSL/TLS、用户名填 <code>resend</code>。
|
||||||
|
其他服务商请填写其官方 SMTP 地址。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="smtp-row">
|
||||||
|
<div>
|
||||||
|
<label for="smtpPort">端口</label>
|
||||||
|
<input type="number" id="smtpPort" placeholder="587" min="1" max="65535" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label for="smtpSecure">加密方式</label>
|
||||||
|
<select id="smtpSecure">
|
||||||
|
<option value="false">STARTTLS(587)</option>
|
||||||
|
<option value="true">SSL/TLS(465)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label for="smtpUser">用户名</label>
|
||||||
|
<input type="text" id="smtpUser" placeholder="通常为完整邮箱地址" autocomplete="off" />
|
||||||
|
|
||||||
|
<label for="smtpPassword">密码 / 授权码</label>
|
||||||
|
<input type="password" id="smtpPassword" placeholder="留空表示不修改已保存的密码" autocomplete="new-password" />
|
||||||
|
<div class="smtp-hint">
|
||||||
|
QQ、163 等邮箱填「授权码」;<strong>Resend 填 API Key</strong>(re_ 开头)。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label for="smtpFromName">发件人名称</label>
|
||||||
|
<input type="text" id="smtpFromName" placeholder="例如:论坛名称" />
|
||||||
|
|
||||||
|
<label for="smtpFromEmail">发件人邮箱 <span style="color:#ef4444;">*</span></label>
|
||||||
|
<input type="email" id="smtpFromEmail" placeholder="noreply@example.com" />
|
||||||
|
<div class="smtp-hint">
|
||||||
|
必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="smtp-check" style="margin-bottom:20px;">
|
||||||
|
<input type="checkbox" id="smtpAllowSelfSigned" />
|
||||||
|
允许自签证书(仅自建邮件服务器需要)
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="smtp-actions">
|
||||||
|
<button id="smtpSaveBtn" class="btn-primary" style="padding:10px 22px;">保存配置</button>
|
||||||
|
<button id="smtpTestBtn" class="btn-secondary" style="padding:10px 22px;">发送测试邮件</button>
|
||||||
|
<button id="smtpClearPwBtn" class="btn-secondary" style="padding:10px 22px;">清除密码</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<hr />
|
||||||
|
|
||||||
|
<h4 style="font-size:15px;margin-bottom:6px;">注册邮箱验证</h4>
|
||||||
|
<p style="font-size:13px;color:var(--text-secondary);margin-bottom:12px;">
|
||||||
|
开启后,新用户注册必须填写邮箱收到的验证码。需先完成上方配置并确保测试邮件可送达。
|
||||||
|
</p>
|
||||||
|
<label class="smtp-check" style="margin-bottom:0;">
|
||||||
|
<input type="checkbox" id="emailVerifyRequired" />
|
||||||
|
要求注册时验证邮箱
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
const $ = id => document.getElementById(id);
|
||||||
|
|
||||||
|
// 载入现有配置
|
||||||
|
API.getSmtpConfig().then(cfg => {
|
||||||
|
$('smtpEnabled').checked = cfg.enabled;
|
||||||
|
$('smtpHost').value = cfg.host || '';
|
||||||
|
$('smtpPort').value = cfg.port || 587;
|
||||||
|
$('smtpSecure').value = String(cfg.secure);
|
||||||
|
$('smtpUser').value = cfg.user || '';
|
||||||
|
$('smtpFromName').value = cfg.from_name || '';
|
||||||
|
$('smtpFromEmail').value = cfg.from_email || '';
|
||||||
|
$('smtpAllowSelfSigned').checked = cfg.allow_self_signed === true;
|
||||||
|
// 密码永不回显,只用占位文字提示是否已设置
|
||||||
|
$('smtpPassword').placeholder = cfg.password_set
|
||||||
|
? '已保存密码,留空则不修改'
|
||||||
|
: '尚未设置密码';
|
||||||
|
|
||||||
|
const status = $('smtpStatus');
|
||||||
|
if (cfg.configured) {
|
||||||
|
status.innerHTML = `${getIcon('success')} 配置完整,可以发信`;
|
||||||
|
status.style.background = 'rgba(34,197,94,0.12)';
|
||||||
|
status.style.color = '#16a34a';
|
||||||
|
} else {
|
||||||
|
status.innerHTML = `${getIcon('warning')} 尚未配置完成,邮件功能不可用`;
|
||||||
|
status.style.background = 'rgba(245,158,11,0.12)';
|
||||||
|
status.style.color = '#d97706';
|
||||||
|
}
|
||||||
|
}).catch(err => {
|
||||||
|
showToast('加载配置失败:' + err.message, 'error');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 读取邮箱验证开关(该值在公开设置接口中)
|
||||||
|
API.getSettings().then(s => {
|
||||||
|
$('emailVerifyRequired').checked = s.email_verify_required === true;
|
||||||
|
}).catch(() => {});
|
||||||
|
|
||||||
|
$('smtpSaveBtn').addEventListener('click', async () => {
|
||||||
|
const payload = {
|
||||||
|
enabled: $('smtpEnabled').checked,
|
||||||
|
host: $('smtpHost').value.trim(),
|
||||||
|
port: Number($('smtpPort').value || 587),
|
||||||
|
secure: $('smtpSecure').value === 'true',
|
||||||
|
user: $('smtpUser').value.trim(),
|
||||||
|
from_name: $('smtpFromName').value.trim(),
|
||||||
|
from_email: $('smtpFromEmail').value.trim(),
|
||||||
|
allow_self_signed: $('smtpAllowSelfSigned').checked,
|
||||||
|
};
|
||||||
|
// 只有填了才提交,避免把已保存的密码覆盖成空
|
||||||
|
const pw = $('smtpPassword').value;
|
||||||
|
if (pw) payload.password = pw;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await API.saveSmtpConfig(payload);
|
||||||
|
$('smtpPassword').value = '';
|
||||||
|
showToast('配置已保存', 'success');
|
||||||
|
renderAdminSmtp();
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('smtpTestBtn').addEventListener('click', async function() {
|
||||||
|
const btn = this;
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = '发送中…';
|
||||||
|
try {
|
||||||
|
const r = await API.sendTestMail();
|
||||||
|
showToast('测试邮件已发送至 ' + r.to, 'success');
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '发送测试邮件';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('smtpClearPwBtn').addEventListener('click', async () => {
|
||||||
|
const ok = await showConfirm('确定要清除已保存的 SMTP 密码吗?', {
|
||||||
|
title: '清除密码', confirmText: '清除', danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
|
try {
|
||||||
|
await API.clearSmtpPassword();
|
||||||
|
showToast('密码已清除', 'success');
|
||||||
|
renderAdminSmtp();
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$('emailVerifyRequired').addEventListener('change', async function() {
|
||||||
|
const desired = this.checked;
|
||||||
|
try {
|
||||||
|
await API.setEmailVerifyRequired(desired);
|
||||||
|
showToast(desired ? '已开启注册邮箱验证' : '已关闭注册邮箱验证', 'success');
|
||||||
|
} catch (err) {
|
||||||
|
// 失败时把开关状态回滚,避免界面与服务端不一致
|
||||||
|
this.checked = !desired;
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// 🎨 自定义 CSS(独立标签页)- 已改用 Toast 提示
|
// 🎨 自定义 CSS(独立标签页)- 已改用 Toast 提示
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -558,7 +757,12 @@ function renderAdminCustomCSS() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('customCssDeleteBtn').addEventListener('click', async function() {
|
document.getElementById('customCssDeleteBtn').addEventListener('click', async function() {
|
||||||
if (!confirm('确定要删除自定义 CSS 吗?将恢复默认样式。')) return;
|
const ok = await showConfirm('确定要删除自定义 CSS 吗?将恢复默认样式。', {
|
||||||
|
title: '删除自定义 CSS',
|
||||||
|
confirmText: '删除',
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
try {
|
try {
|
||||||
await API.deleteCustomCSS();
|
await API.deleteCustomCSS();
|
||||||
showToast('已删除自定义 CSS', 'success');
|
showToast('已删除自定义 CSS', 'success');
|
||||||
@@ -643,12 +847,15 @@ function loadCustomPageList() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
container.querySelectorAll('[data-action="delete"]').forEach(btn => {
|
container.querySelectorAll('[data-action="delete"]').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', async function() {
|
||||||
if (!confirm('确定要删除这个页面吗?')) return;
|
const ok = await showConfirm('确定要删除这个页面吗?', {
|
||||||
|
title: '删除页面', confirmText: '删除', danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
API.deleteCustomPage(this.dataset.id).then(() => {
|
API.deleteCustomPage(this.dataset.id).then(() => {
|
||||||
loadCustomPageList();
|
loadCustomPageList();
|
||||||
loadCustomPagesNav();
|
loadCustomPagesNav();
|
||||||
}).catch(err => alert('删除失败:' + err.message));
|
}).catch(err => showToast('删除失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
@@ -707,11 +914,11 @@ function openCustomPageEditor(page) {
|
|||||||
const content = document.getElementById('editorContent').value.trim();
|
const content = document.getElementById('editorContent').value.trim();
|
||||||
const enabled = document.getElementById('editorEnabled').value === 'true';
|
const enabled = document.getElementById('editorEnabled').value === 'true';
|
||||||
|
|
||||||
if (!name) { alert('请输入页面名称'); return; }
|
if (!name) { showToast('请输入页面名称', 'warning'); return; }
|
||||||
if (!title) { alert('请输入导航栏显示名称'); return; }
|
if (!title) { showToast('请输入导航栏显示名称', 'warning'); return; }
|
||||||
if (!content) { alert('请输入页面内容'); return; }
|
if (!content) { showToast('请输入页面内容', 'warning'); return; }
|
||||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
|
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
|
||||||
alert('页面名称只允许字母、数字、短横线和下划线');
|
showToast('页面名称只允许字母、数字、短横线和下划线', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -725,7 +932,7 @@ function openCustomPageEditor(page) {
|
|||||||
loadCustomPageList();
|
loadCustomPageList();
|
||||||
loadCustomPagesNav();
|
loadCustomPagesNav();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('保存失败:' + err.message);
|
showToast('保存失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -813,6 +1020,7 @@ document.querySelector('.admin-nav')?.addEventListener('click', function(e) {
|
|||||||
links: renderAdminLinks,
|
links: renderAdminLinks,
|
||||||
'custom-css': renderAdminCustomCSS,
|
'custom-css': renderAdminCustomCSS,
|
||||||
settings: renderAdminSettings,
|
settings: renderAdminSettings,
|
||||||
|
smtp: renderAdminSmtp,
|
||||||
custom: renderAdminCustomPages
|
custom: renderAdminCustomPages
|
||||||
};
|
};
|
||||||
if (tabMap[tab]) tabMap[tab]();
|
if (tabMap[tab]) tabMap[tab]();
|
||||||
|
|||||||
@@ -37,10 +37,16 @@ const API = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
async register(email, password, username, bootstrapToken = '') {
|
async register(email, password, username, bootstrapToken = '', emailCode = '') {
|
||||||
const data = await apiFetch('/auth/register', {
|
const data = await apiFetch('/auth/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({ email, password, username, bootstrap_token: bootstrapToken || undefined })
|
body: JSON.stringify({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
username,
|
||||||
|
bootstrap_token: bootstrapToken || undefined,
|
||||||
|
email_code: emailCode || undefined
|
||||||
|
})
|
||||||
});
|
});
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
return data;
|
return data;
|
||||||
@@ -67,6 +73,15 @@ const API = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 搜索帖子(标题与正文)
|
||||||
|
async searchPosts(keyword, page = 1, limit = 20) {
|
||||||
|
const data = await apiFetch(
|
||||||
|
'/posts/search?q=' + encodeURIComponent(keyword) + '&page=' + page + '&limit=' + limit
|
||||||
|
);
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async getPost(postId) {
|
async getPost(postId) {
|
||||||
const data = await apiFetch('/posts/' + postId);
|
const data = await apiFetch('/posts/' + postId);
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
@@ -257,6 +272,42 @@ const API = {
|
|||||||
return data || [];
|
return data || [];
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 搜索用户(用于发起私信)。仅返回用户名、头像等公开信息。
|
||||||
|
async searchUsers(keyword, limit = 10) {
|
||||||
|
const data = await apiFetch(
|
||||||
|
'/users/search?q=' + encodeURIComponent(keyword) + '&limit=' + limit
|
||||||
|
);
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data.data || [];
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 用户屏蔽
|
||||||
|
// ============================================================
|
||||||
|
async blockUser(userId) {
|
||||||
|
const data = await apiFetch('/users/' + userId + '/block', { method: 'POST' });
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async unblockUser(userId) {
|
||||||
|
const data = await apiFetch('/users/' + userId + '/block', { method: 'DELETE' });
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async getBlockedUsers() {
|
||||||
|
const data = await apiFetch('/blocks');
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data.data || [];
|
||||||
|
},
|
||||||
|
|
||||||
|
async getBlockStatus(userId) {
|
||||||
|
const data = await apiFetch('/users/' + userId + '/block-status');
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async getOrCreateConversation(other_user_id) {
|
async getOrCreateConversation(other_user_id) {
|
||||||
const data = await apiFetch('/conversations', {
|
const data = await apiFetch('/conversations', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -442,5 +493,80 @@ const API = {
|
|||||||
});
|
});
|
||||||
if (data.error) throw new Error(data.error);
|
if (data.error) throw new Error(data.error);
|
||||||
return data;
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// SMTP 配置(管理员)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
async getSmtpConfig() {
|
||||||
|
const data = await apiFetch('/admin/smtp');
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// password 留空表示保持原有密码不变
|
||||||
|
async saveSmtpConfig(config) {
|
||||||
|
const data = await apiFetch('/admin/smtp', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(config)
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async clearSmtpPassword() {
|
||||||
|
const data = await apiFetch('/admin/smtp/password', { method: 'DELETE' });
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async sendTestMail(to) {
|
||||||
|
const data = await apiFetch('/admin/smtp/test', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(to ? { to } : {})
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async setEmailVerifyRequired(required) {
|
||||||
|
const data = await apiFetch('/admin/email-verify', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ required })
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 邮箱验证码
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
async sendRegisterCode(email) {
|
||||||
|
const data = await apiFetch('/auth/send-code', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ email })
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async forgotPassword(email) {
|
||||||
|
const data = await apiFetch('/auth/forgot-password', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ email })
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async resetPasswordByEmail(email, code, newPassword) {
|
||||||
|
const data = await apiFetch('/auth/reset-password-by-email', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ email, code, newPassword })
|
||||||
|
});
|
||||||
|
if (data.error) throw new Error(data.error);
|
||||||
|
return data;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -3,6 +3,143 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
let currentUser = null;
|
let currentUser = null;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 带出场动画的关闭
|
||||||
|
// ============================================================
|
||||||
|
// .modal 与 .dropdown-menu 的默认状态是 display:none,直接移除类名会让
|
||||||
|
// 元素瞬间消失,CSS 动画没有机会播放。这里先挂上 .closing 播放收起
|
||||||
|
// 动画,等 animationend 再移除类名恢复默认状态。
|
||||||
|
//
|
||||||
|
// 用 requestAnimationFrame 等待样式生效后再挂类,避免元素在同一帧内
|
||||||
|
// 被移除而跳过动画;animationend 同时兜底超时,防止动画未触发时卡住。
|
||||||
|
|
||||||
|
const CLOSING_CLASS = 'closing';
|
||||||
|
const CLOSE_FALLBACK_MS = 260;
|
||||||
|
|
||||||
|
function closeWithAnimation(el, className) {
|
||||||
|
if (!el || !el.classList.contains(className)) return;
|
||||||
|
// 已经在收起过程中则忽略重复调用
|
||||||
|
if (el.classList.contains(CLOSING_CLASS)) return;
|
||||||
|
|
||||||
|
let finished = false;
|
||||||
|
const finish = () => {
|
||||||
|
if (finished) return;
|
||||||
|
finished = true;
|
||||||
|
el.classList.remove(CLOSING_CLASS);
|
||||||
|
el.classList.remove(className);
|
||||||
|
el.removeEventListener('animationend', onEnd);
|
||||||
|
};
|
||||||
|
const onEnd = event => {
|
||||||
|
if (event.target === el) finish();
|
||||||
|
};
|
||||||
|
|
||||||
|
el.addEventListener('animationend', onEnd);
|
||||||
|
// 元素不可见(无动画)或动画被浏览器跳过时兜底
|
||||||
|
const fallback = setTimeout(finish, CLOSE_FALLBACK_MS);
|
||||||
|
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
// 若期间元素被重新打开(类名已被移除),取消本次关闭,
|
||||||
|
// 否则会把 .closing 挂到一个本应显示的弹窗上。
|
||||||
|
if (!el.classList.contains(className) || finished) {
|
||||||
|
clearTimeout(fallback);
|
||||||
|
el.removeEventListener('animationend', onEnd);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.classList.add(CLOSING_CLASS);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeModal = el => closeWithAnimation(el, 'active');
|
||||||
|
const closeDropdown = el => closeWithAnimation(el, 'show');
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 确认对话框
|
||||||
|
// ============================================================
|
||||||
|
// 替代浏览器原生 confirm():原生弹窗样式无法定制、会阻塞渲染线程,
|
||||||
|
// 在移动端尤其突兀。这里返回 Promise<boolean>,配合 await 使用:
|
||||||
|
//
|
||||||
|
// if (!await showConfirm('确定删除吗?')) return;
|
||||||
|
//
|
||||||
|
// 支持 Esc 取消、点击遮罩取消、危险操作红色按钮,并复用模态框的
|
||||||
|
// 进出场动画。
|
||||||
|
|
||||||
|
function showConfirm(message, options = {}) {
|
||||||
|
const {
|
||||||
|
title = '请确认',
|
||||||
|
confirmText = '确定',
|
||||||
|
cancelText = '取消',
|
||||||
|
danger = false,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
return new Promise(resolve => {
|
||||||
|
let settled = false;
|
||||||
|
const modal = document.createElement('div');
|
||||||
|
modal.className = 'modal confirm-modal';
|
||||||
|
|
||||||
|
// 用 textContent 而非模板字符串拼接,避免消息里的特殊字符被当作 HTML
|
||||||
|
modal.innerHTML = `
|
||||||
|
<div class="modal-content" style="max-width:380px;">
|
||||||
|
<h2 class="confirm-title"></h2>
|
||||||
|
<p class="confirm-message"></p>
|
||||||
|
<div class="confirm-actions">
|
||||||
|
<button class="btn-secondary confirm-cancel" type="button"></button>
|
||||||
|
<button class="btn-primary confirm-ok" type="button"></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
modal.querySelector('.confirm-title').textContent = title;
|
||||||
|
modal.querySelector('.confirm-message').textContent = message;
|
||||||
|
modal.querySelector('.confirm-cancel').textContent = cancelText;
|
||||||
|
const okBtn = modal.querySelector('.confirm-ok');
|
||||||
|
okBtn.textContent = confirmText;
|
||||||
|
if (danger) okBtn.classList.add('btn-danger-solid');
|
||||||
|
|
||||||
|
document.body.appendChild(modal);
|
||||||
|
|
||||||
|
const cleanup = () => {
|
||||||
|
document.removeEventListener('keydown', onKey);
|
||||||
|
closeModal(modal);
|
||||||
|
// 等出场动画结束再移除节点,与 closeWithAnimation 的兜底时长一致
|
||||||
|
setTimeout(() => modal.remove(), 300);
|
||||||
|
};
|
||||||
|
|
||||||
|
const settle = value => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
cleanup();
|
||||||
|
resolve(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKey = event => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
settle(false);
|
||||||
|
} else if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
settle(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
okBtn.addEventListener('click', () => settle(true));
|
||||||
|
modal.querySelector('.confirm-cancel').addEventListener('click', () => settle(false));
|
||||||
|
|
||||||
|
// 点击遮罩(内容区之外)视为取消
|
||||||
|
modal.addEventListener('click', event => {
|
||||||
|
if (event.target === modal) settle(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('keydown', onKey);
|
||||||
|
|
||||||
|
// 下一帧再加 .active,确保入场动画能播放
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
modal.classList.add('active');
|
||||||
|
okBtn.focus();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function showToast(message, type = 'success', duration = 3000) {
|
function showToast(message, type = 'success', duration = 3000) {
|
||||||
// 移除已有 toast
|
// 移除已有 toast
|
||||||
const existing = document.querySelector('.toast');
|
const existing = document.querySelector('.toast');
|
||||||
@@ -69,6 +206,105 @@ async function loadForumName() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 页面转场
|
||||||
|
// ============================================================
|
||||||
|
// 打开一个覆盖页时:
|
||||||
|
// 1. 首页(#app)留在原位,缩小并后退,同时叠加暗色遮罩 → 「下沉」
|
||||||
|
// 2. 新页面从屏幕之外滑入,并由 0.94 放大到 1
|
||||||
|
// 关闭时反向播放:新页面滑出屏幕,首页上浮回原位。
|
||||||
|
//
|
||||||
|
// 关键点:首页不再被 display:none 直接隐藏,否则整段动画无从谈起。
|
||||||
|
// 只有在转场完全结束后才把它藏起来,避免它继续响应点击或影响滚动。
|
||||||
|
|
||||||
|
const TRANSITION_MS = 420;
|
||||||
|
|
||||||
|
function sinkBackground() {
|
||||||
|
const app = document.getElementById('app');
|
||||||
|
if (!app) return;
|
||||||
|
app.classList.remove('page-stack-rise');
|
||||||
|
app.classList.add('page-stack-sink');
|
||||||
|
document.body.classList.add('page-stack-open');
|
||||||
|
}
|
||||||
|
|
||||||
|
function riseBackground() {
|
||||||
|
const app = document.getElementById('app');
|
||||||
|
document.body.classList.remove('page-stack-open');
|
||||||
|
if (!app) return;
|
||||||
|
app.classList.remove('page-stack-sink');
|
||||||
|
app.classList.add('page-stack-rise');
|
||||||
|
// 动画结束后移除类,避免遗留的 transform 影响 sticky 定位等
|
||||||
|
window.setTimeout(() => app.classList.remove('page-stack-rise'), TRANSITION_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 展示某个覆盖页:先让背景下沉,再挂上 active 触发滑入
|
||||||
|
function showSlide(el, { back = false } = {}) {
|
||||||
|
if (!el) return;
|
||||||
|
// 清掉上一次的退出状态
|
||||||
|
el.classList.remove('slide-out', 'slide-out-back', 'slide-back');
|
||||||
|
if (back) el.classList.add('slide-back');
|
||||||
|
el.classList.add('active');
|
||||||
|
// 强制重排以重放动画(同一元素连续切换时需要)
|
||||||
|
el.style.animation = 'none';
|
||||||
|
void el.offsetHeight;
|
||||||
|
el.style.animation = '';
|
||||||
|
|
||||||
|
// 首页仍在文档流中,需要让出滚动位置
|
||||||
|
sinkBackground();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭覆盖页:播退出动画,结束后清理状态并让首页上浮
|
||||||
|
function hideSlide(el, { back = false, onDone } = {}) {
|
||||||
|
if (!el) {
|
||||||
|
riseBackground();
|
||||||
|
if (onDone) onDone();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.classList.remove('active', 'slide-back');
|
||||||
|
el.classList.add('slide-out');
|
||||||
|
if (back) el.classList.add('slide-out-back');
|
||||||
|
|
||||||
|
riseBackground();
|
||||||
|
|
||||||
|
window.setTimeout(() => {
|
||||||
|
el.classList.remove('slide-out', 'slide-out-back');
|
||||||
|
if (onDone) onDone();
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 返回首页:当前覆盖页向左滑出,首页从下沉状态上浮回原位。
|
||||||
|
// 与浏览器后退键走同一条路径,保证两种方式的方向感一致。
|
||||||
|
function navigateBackToFeed() {
|
||||||
|
const currentSlide = document.querySelector('.page-slide.active');
|
||||||
|
|
||||||
|
// 同步 URL:去掉页面参数,回到纯首页地址
|
||||||
|
const url = new URL(window.location);
|
||||||
|
url.searchParams.delete('page');
|
||||||
|
url.searchParams.delete('post');
|
||||||
|
url.searchParams.delete('user');
|
||||||
|
url.searchParams.delete('custom');
|
||||||
|
window.history.pushState({ page: 'feed' }, '', url);
|
||||||
|
|
||||||
|
if (currentSlide) {
|
||||||
|
hideSlide(currentSlide, { back: true, onDone: () => {
|
||||||
|
document.getElementById('app').style.display = 'flex';
|
||||||
|
} });
|
||||||
|
} else {
|
||||||
|
document.getElementById('app').style.display = 'flex';
|
||||||
|
riseBackground();
|
||||||
|
}
|
||||||
|
|
||||||
|
const customContainer = document.getElementById('customPageContainer');
|
||||||
|
if (customContainer && customContainer.classList.contains('active')) {
|
||||||
|
hideSlide(customContainer, { back: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
currentPage = 'feed';
|
||||||
|
renderFeed();
|
||||||
|
renderStats();
|
||||||
|
renderLinks();
|
||||||
|
}
|
||||||
|
|
||||||
function switchPage(page, param) {
|
function switchPage(page, param) {
|
||||||
const url = new URL(window.location);
|
const url = new URL(window.location);
|
||||||
|
|
||||||
@@ -113,19 +349,34 @@ function switchPage(page, param) {
|
|||||||
}
|
}
|
||||||
window.history.pushState({ page: page }, '', url);
|
window.history.pushState({ page: page }, '', url);
|
||||||
|
|
||||||
document.getElementById('app').style.display = 'none';
|
// 转场开始:先记录当前显示的覆盖页,稍后让它滑出
|
||||||
document.querySelectorAll('.page-slide').forEach(el => {
|
const currentSlide = document.querySelector('.page-slide.active');
|
||||||
el.classList.remove('active', 'slide-out');
|
const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
|
||||||
});
|
|
||||||
|
// 目标页就是当前页时无需转场
|
||||||
|
const pageMap = {
|
||||||
|
messages: 'pageMessages',
|
||||||
|
settings: 'pageSettings',
|
||||||
|
admin: 'pageAdmin',
|
||||||
|
new: 'pageNew'
|
||||||
|
};
|
||||||
|
const targetEl = page === 'feed' ? null : document.getElementById(pageMap[page]);
|
||||||
|
if (currentSlide && targetEl && currentSlide === targetEl) return;
|
||||||
|
|
||||||
|
// 旧覆盖页滑出
|
||||||
|
if (currentSlide && currentSlide !== targetEl) {
|
||||||
|
hideSlide(currentSlide, { back: goingBack });
|
||||||
|
}
|
||||||
|
|
||||||
const customContainer = document.getElementById('customPageContainer');
|
const customContainer = document.getElementById('customPageContainer');
|
||||||
if (customContainer) {
|
if (customContainer && customContainer.classList.contains('active')) {
|
||||||
customContainer.classList.remove('active');
|
hideSlide(customContainer);
|
||||||
customContainer.style.display = 'none';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (page === 'feed') {
|
if (page === 'feed') {
|
||||||
|
// 回到首页:首页上浮回原位,不需要显示任何覆盖页
|
||||||
document.getElementById('app').style.display = 'flex';
|
document.getElementById('app').style.display = 'flex';
|
||||||
|
riseBackground();
|
||||||
currentPage = 'feed';
|
currentPage = 'feed';
|
||||||
renderFeed();
|
renderFeed();
|
||||||
renderStats();
|
renderStats();
|
||||||
@@ -133,18 +384,9 @@ function switchPage(page, param) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const pageMap = {
|
const el = targetEl;
|
||||||
messages: 'pageMessages',
|
|
||||||
settings: 'pageSettings',
|
|
||||||
admin: 'pageAdmin',
|
|
||||||
new: 'pageNew'
|
|
||||||
};
|
|
||||||
const el = document.getElementById(pageMap[page]);
|
|
||||||
if (el) {
|
if (el) {
|
||||||
el.classList.add('active');
|
showSlide(el, { back: goingBack });
|
||||||
el.style.animation = 'none';
|
|
||||||
void el.offsetHeight;
|
|
||||||
el.style.animation = '';
|
|
||||||
currentPage = page;
|
currentPage = page;
|
||||||
|
|
||||||
if (page === 'admin') {
|
if (page === 'admin') {
|
||||||
@@ -198,11 +440,236 @@ async function updateUnreadBadge() {
|
|||||||
|
|
||||||
function openMessageList() {
|
function openMessageList() {
|
||||||
document.getElementById('messageListModal').classList.add('active');
|
document.getElementById('messageListModal').classList.add('active');
|
||||||
|
// 每次打开都回到会话列表状态,避免上次的搜索词或「已屏蔽」视图残留
|
||||||
|
const searchInput = document.getElementById('dmUserSearchInput');
|
||||||
|
if (searchInput) searchInput.value = '';
|
||||||
|
syncDmSearchClear();
|
||||||
|
const tabConv = document.getElementById('dmTabConversations');
|
||||||
|
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||||
|
if (tabConv) tabConv.classList.add('active');
|
||||||
|
if (tabBlocked) tabBlocked.classList.remove('active');
|
||||||
renderMessageList();
|
renderMessageList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ✉️ 私信:按用户名搜索并直接开聊
|
||||||
|
// ============================================================
|
||||||
|
// 此前只能进入对方个人主页再点「私信」,这里提供直接搜索的入口。
|
||||||
|
|
||||||
|
function syncDmSearchClear() {
|
||||||
|
const input = document.getElementById('dmUserSearchInput');
|
||||||
|
const btn = document.getElementById('dmUserSearchClear');
|
||||||
|
if (input && btn) btn.style.display = input.value.trim() ? 'flex' : 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderDmUserSearch(keyword) {
|
||||||
|
const container = document.getElementById('messageListContent');
|
||||||
|
const kw = (keyword || '').trim();
|
||||||
|
|
||||||
|
if (!kw) {
|
||||||
|
renderMessageList();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
container.innerHTML = '<div class="dm-search-status">搜索中…</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const users = await API.searchUsers(kw, 10);
|
||||||
|
|
||||||
|
// 排除自己
|
||||||
|
const others = users.filter(u => !currentUser || u.id !== currentUser.id);
|
||||||
|
|
||||||
|
if (others.length === 0) {
|
||||||
|
container.innerHTML = '<div class="dm-search-status">没有找到匹配的用户</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
others.forEach(u => {
|
||||||
|
const avatar = u.avatar_url ||
|
||||||
|
'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64';
|
||||||
|
html += `
|
||||||
|
<div class="dm-user-row" data-user-id="${escapeHTML(u.id)}" data-username="${escapeHTML(u.username)}">
|
||||||
|
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" alt="" />
|
||||||
|
<div class="dm-user-info">
|
||||||
|
<div class="dm-user-name">${escapeHTML(u.username)}</div>
|
||||||
|
<div class="dm-user-hint">${escapeHTML(u.signature || '点击发送私信')}</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="dm-user-block" data-user-id="${escapeHTML(u.id)}"
|
||||||
|
data-username="${escapeHTML(u.username)}" title="屏蔽该用户">屏蔽</button>
|
||||||
|
<span class="dm-user-action">私信</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
container.innerHTML = sanitizeHTML(html);
|
||||||
|
|
||||||
|
// 屏蔽按钮:需与行点击区分开,因此阻止冒泡
|
||||||
|
container.querySelectorAll('.dm-user-block').forEach(btn => {
|
||||||
|
btn.addEventListener('click', async function(e) {
|
||||||
|
e.stopPropagation();
|
||||||
|
const userId = this.dataset.userId;
|
||||||
|
const username = this.dataset.username;
|
||||||
|
|
||||||
|
const ok = await showConfirm(
|
||||||
|
`确定屏蔽「${username}」?屏蔽后你不再看到 TA 的帖子和回复,TA 也无法给你发私信。`,
|
||||||
|
{ title: '屏蔽用户', confirmText: '屏蔽', danger: true }
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await API.blockUser(userId);
|
||||||
|
showToast('已屏蔽该用户', 'success');
|
||||||
|
// 屏蔽后该用户不应再出现于搜索结果中,重新执行一次搜索
|
||||||
|
renderDmUserSearch(document.getElementById('dmUserSearchInput').value);
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
container.querySelectorAll('.dm-user-row').forEach(row => {
|
||||||
|
row.addEventListener('click', async function() {
|
||||||
|
const userId = this.dataset.userId;
|
||||||
|
const username = this.dataset.username;
|
||||||
|
try {
|
||||||
|
const conv = await API.getOrCreateConversation(userId);
|
||||||
|
// 关闭搜索状态,进入聊天窗口
|
||||||
|
const searchInput = document.getElementById('dmUserSearchInput');
|
||||||
|
if (searchInput) searchInput.value = '';
|
||||||
|
syncDmSearchClear();
|
||||||
|
// openChat 需要三个参数:会话 ID、对方用户 ID、对方用户名
|
||||||
|
openChat(conv.id, userId, username);
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
container.innerHTML = '<div class="dm-search-status">搜索失败:' + escapeHTML(err.message) + '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 绑定搜索框事件(防抖 300ms)
|
||||||
|
(function initDmUserSearch() {
|
||||||
|
const input = document.getElementById('dmUserSearchInput');
|
||||||
|
const clearBtn = document.getElementById('dmUserSearchClear');
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
let timer = null;
|
||||||
|
|
||||||
|
function run() {
|
||||||
|
syncDmSearchClear();
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(() => renderDmUserSearch(input.value), 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
input.addEventListener('input', run);
|
||||||
|
|
||||||
|
input.addEventListener('keydown', e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
renderDmUserSearch(input.value);
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault();
|
||||||
|
input.value = '';
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
renderDmUserSearch('');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (clearBtn) {
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
input.value = '';
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
renderDmUserSearch('');
|
||||||
|
input.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// 渲染「已屏蔽」列表
|
||||||
|
async function renderBlockedUsers() {
|
||||||
|
const container = document.getElementById('messageListContent');
|
||||||
|
container.innerHTML = '<div class="dm-search-status">加载中…</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const users = await API.getBlockedUsers();
|
||||||
|
if (users.length === 0) {
|
||||||
|
container.innerHTML = '<div class="dm-search-status">还没有屏蔽任何人</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '';
|
||||||
|
users.forEach(u => {
|
||||||
|
const avatar = u.avatar_url ||
|
||||||
|
'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64';
|
||||||
|
html += `
|
||||||
|
<div class="dm-user-row" style="cursor:default;">
|
||||||
|
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" alt="" />
|
||||||
|
<div class="dm-user-info">
|
||||||
|
<div class="dm-user-name">${escapeHTML(u.username)}</div>
|
||||||
|
<div class="dm-user-hint">屏蔽于 ${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '未知'}</div>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="dm-user-unblock"
|
||||||
|
data-user-id="${escapeHTML(u.id)}" data-username="${escapeHTML(u.username)}">解除屏蔽</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
});
|
||||||
|
container.innerHTML = sanitizeHTML(html);
|
||||||
|
|
||||||
|
container.querySelectorAll('.dm-user-unblock').forEach(btn => {
|
||||||
|
btn.addEventListener('click', async function() {
|
||||||
|
const userId = this.dataset.userId;
|
||||||
|
const username = this.dataset.username;
|
||||||
|
|
||||||
|
const ok = await showConfirm(
|
||||||
|
`解除对「${username}」的屏蔽?解除后你将继续看到 TA 的帖子和回复,TA 也能再次给你发私信。`,
|
||||||
|
{ title: '解除屏蔽', confirmText: '解除屏蔽' }
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await API.unblockUser(userId);
|
||||||
|
showToast('已解除屏蔽', 'success');
|
||||||
|
renderBlockedUsers();
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
container.innerHTML = '<div class="dm-search-status">加载失败</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 视图切换:会话 / 已屏蔽
|
||||||
|
function switchDmView(view) {
|
||||||
|
const tabConv = document.getElementById('dmTabConversations');
|
||||||
|
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||||
|
if (tabConv) tabConv.classList.toggle('active', view === 'conversations');
|
||||||
|
if (tabBlocked) tabBlocked.classList.toggle('active', view === 'blocked');
|
||||||
|
|
||||||
|
// 切到已屏蔽时清空搜索框,避免搜索状态与列表视图混淆
|
||||||
|
const input = document.getElementById('dmUserSearchInput');
|
||||||
|
if (view === 'blocked' && input) {
|
||||||
|
input.value = '';
|
||||||
|
syncDmSearchClear();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (view === 'blocked') renderBlockedUsers();
|
||||||
|
else renderMessageList();
|
||||||
|
}
|
||||||
|
|
||||||
|
(function initDmTabs() {
|
||||||
|
const tabConv = document.getElementById('dmTabConversations');
|
||||||
|
const tabBlocked = document.getElementById('dmTabBlocked');
|
||||||
|
if (tabConv) tabConv.addEventListener('click', () => switchDmView('conversations'));
|
||||||
|
if (tabBlocked) tabBlocked.addEventListener('click', () => switchDmView('blocked'));
|
||||||
|
})();
|
||||||
|
|
||||||
function closeMessageList() {
|
function closeMessageList() {
|
||||||
document.getElementById('messageListModal').classList.remove('active');
|
closeModal(document.getElementById('messageListModal'));
|
||||||
if (messagePollInterval) {
|
if (messagePollInterval) {
|
||||||
clearInterval(messagePollInterval);
|
clearInterval(messagePollInterval);
|
||||||
messagePollInterval = null;
|
messagePollInterval = null;
|
||||||
@@ -272,7 +739,7 @@ function openChat(conversationId, otherUserId, otherUsername) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function closeChat() {
|
function closeChat() {
|
||||||
document.getElementById('chatModal').classList.remove('active');
|
closeModal(document.getElementById('chatModal'));
|
||||||
if (messagePollInterval) {
|
if (messagePollInterval) {
|
||||||
clearInterval(messagePollInterval);
|
clearInterval(messagePollInterval);
|
||||||
messagePollInterval = null;
|
messagePollInterval = null;
|
||||||
@@ -283,6 +750,38 @@ function closeChat() {
|
|||||||
updateUnreadBadge();
|
updateUnreadBadge();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 更新聊天窗口底部的发送限制提示。
|
||||||
|
// 规则:对方从未回复时,我方最多先发 3 条(与后端
|
||||||
|
// NEW_CONVERSATION_MESSAGE_LIMIT 对应)。对方回复过就不再限制,
|
||||||
|
// 此时隐藏提示条。
|
||||||
|
const DM_FIRST_ROUND_LIMIT = 3;
|
||||||
|
|
||||||
|
function updateChatLimitNote(messages) {
|
||||||
|
const note = document.getElementById('chatLimitNote');
|
||||||
|
if (!note || !currentUser) return;
|
||||||
|
|
||||||
|
const mine = messages.filter(m => m.sender_id === currentUser.id).length;
|
||||||
|
const theirs = messages.filter(m => m.sender_id !== currentUser.id).length;
|
||||||
|
|
||||||
|
if (theirs > 0) {
|
||||||
|
// 对方已回复,限制解除
|
||||||
|
note.style.display = 'none';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const remaining = Math.max(0, DM_FIRST_ROUND_LIMIT - mine);
|
||||||
|
note.style.display = 'block';
|
||||||
|
// 数字与文字分开放进不同元素:整句含动态数字时 i18n 匹配不到词典,
|
||||||
|
// 拆开后固定文案可被翻译。
|
||||||
|
if (remaining > 0) {
|
||||||
|
note.innerHTML = '<span>对方回复前还可发送</span> '
|
||||||
|
+ '<strong>' + remaining + '</strong> '
|
||||||
|
+ '<span>条消息</span>';
|
||||||
|
} else {
|
||||||
|
note.textContent = '对方回复前无法继续发送,请等待对方回复';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function renderMessages(conversationId, silent = false) {
|
async function renderMessages(conversationId, silent = false) {
|
||||||
const container = document.getElementById('chatMessages');
|
const container = document.getElementById('chatMessages');
|
||||||
if (!silent) {
|
if (!silent) {
|
||||||
@@ -291,6 +790,7 @@ async function renderMessages(conversationId, silent = false) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const messages = await API.getMessages(conversationId);
|
const messages = await API.getMessages(conversationId);
|
||||||
|
updateChatLimitNote(messages);
|
||||||
if (messages.length === 0) {
|
if (messages.length === 0) {
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧</div>';
|
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">还没有消息,打个招呼吧</div>';
|
||||||
return;
|
return;
|
||||||
@@ -337,7 +837,13 @@ async function sendMessage() {
|
|||||||
renderMessageList();
|
renderMessageList();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('发送失败:' + err.message);
|
// 达到首轮发送上限时给出更明确的提示,而不是笼统的「发送失败」
|
||||||
|
if (/最多发送/.test(err.message)) {
|
||||||
|
showToast(err.message, 'warning');
|
||||||
|
renderMessages(currentConversationId, true);
|
||||||
|
} else {
|
||||||
|
showToast('发送失败:' + err.message, 'error');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -360,7 +866,7 @@ async function openPrivateChat(otherUserId, otherUsername) {
|
|||||||
}
|
}
|
||||||
}, 3000);
|
}, 3000);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('打开私信失败:' + err.message);
|
showToast('打开私信失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,15 +889,15 @@ function handleImageFiles(files) {
|
|||||||
|
|
||||||
for (const file of files) {
|
for (const file of files) {
|
||||||
if (selectedImageFiles.length >= 6) {
|
if (selectedImageFiles.length >= 6) {
|
||||||
alert('每篇帖子最多上传 6 张图片');
|
showToast('每篇帖子最多上传 6 张图片', 'warning');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
|
if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
|
||||||
alert('图片 ' + file.name + ' 格式不支持');
|
showToast('图片 ' + file.name + ' 格式不支持', 'error');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (file.size > 5 * 1024 * 1024) {
|
if (file.size > 5 * 1024 * 1024) {
|
||||||
alert('图片 ' + file.name + ' 超过 5MB,请压缩后上传');
|
showToast('图片 ' + file.name + ' 超过 5MB,请压缩后上传', 'warning');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -468,23 +974,25 @@ function renderCustomPagesNav() {
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
function showCustomPage(pageName) {
|
function showCustomPage(pageName) {
|
||||||
document.getElementById('app').style.display = 'none';
|
const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
|
||||||
document.querySelectorAll('.page-slide').forEach(el => {
|
|
||||||
el.classList.remove('active', 'slide-out');
|
|
||||||
});
|
|
||||||
|
|
||||||
let container = document.getElementById('customPageContainer');
|
let container = document.getElementById('customPageContainer');
|
||||||
if (!container) {
|
if (!container) {
|
||||||
container = document.createElement('div');
|
container = document.createElement('div');
|
||||||
container.id = 'customPageContainer';
|
container.id = 'customPageContainer';
|
||||||
container.className = 'page-slide';
|
container.className = 'page-slide';
|
||||||
container.style.cssText = 'display:none;position:fixed;inset:0;background:var(--bg);z-index:50;padding:84px 32px 40px;overflow-y:auto;transition:background 0.2s;';
|
// 不再写内联 display:交给 .page-slide / .active 的样式控制,
|
||||||
|
// 否则会覆盖转场动画所需的 display 切换。
|
||||||
document.body.appendChild(container);
|
document.body.appendChild(container);
|
||||||
}
|
}
|
||||||
|
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
// 先让其他覆盖页滑出
|
||||||
container.classList.add('active');
|
document.querySelectorAll('.page-slide.active').forEach(other => {
|
||||||
container.style.display = 'block';
|
if (other !== container) hideSlide(other, { back: goingBack });
|
||||||
|
});
|
||||||
|
|
||||||
|
container.innerHTML = Skeleton.postDetail();
|
||||||
|
showSlide(container, { back: goingBack });
|
||||||
currentPage = 'custom';
|
currentPage = 'custom';
|
||||||
|
|
||||||
API.getCustomPage(pageName).then(page => {
|
API.getCustomPage(pageName).then(page => {
|
||||||
@@ -774,17 +1282,17 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
const username = document.getElementById('settingsUsername').value.trim();
|
const username = document.getElementById('settingsUsername').value.trim();
|
||||||
const bio = document.getElementById('settingsBio').value.trim();
|
const bio = document.getElementById('settingsBio').value.trim();
|
||||||
const signature = document.getElementById('settingsSignature').value.trim();
|
const signature = document.getElementById('settingsSignature').value.trim();
|
||||||
if (!username) { alert('用户名不能为空'); return; }
|
if (!username) { showToast('用户名不能为空', 'error'); return; }
|
||||||
try {
|
try {
|
||||||
await API.updateProfile(user.id, username, bio, signature);
|
await API.updateProfile(user.id, username, bio, signature);
|
||||||
currentUser.username = username;
|
currentUser.username = username;
|
||||||
currentUser.bio = bio;
|
currentUser.bio = bio;
|
||||||
currentUser.signature = signature;
|
currentUser.signature = signature;
|
||||||
alert('保存成功!');
|
showToast('保存成功!', 'success');
|
||||||
renderNav();
|
renderNav();
|
||||||
renderSettingsPage('profile');
|
renderSettingsPage('profile');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('保存失败:' + err.message);
|
showToast('保存失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -843,12 +1351,13 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
await API.changePassword(oldPassword, newPassword);
|
await API.changePassword(oldPassword, newPassword);
|
||||||
document.getElementById('changeOldPassword').value = '';
|
document.getElementById('changeOldPassword').value = '';
|
||||||
document.getElementById('changeNewPassword').value = '';
|
document.getElementById('changeNewPassword').value = '';
|
||||||
statusEl.textContent = getIcon('success') + ' 密码修改成功,正在返回首页…';
|
// getIcon 返回 SVG 标记,必须用 innerHTML 渲染,否则会把标签当纯文本打印。
|
||||||
|
statusEl.innerHTML = getIcon('success') + ' 密码修改成功,正在返回首页…';
|
||||||
statusEl.style.color = '#22c55e';
|
statusEl.style.color = '#22c55e';
|
||||||
// 服务端已补发新令牌(见 API.changePassword),本次登录保持有效。
|
// 服务端已补发新令牌(见 API.changePassword),本次登录保持有效。
|
||||||
setTimeout(() => switchPage('feed'), 800);
|
setTimeout(() => switchPage('feed'), 800);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
statusEl.innerHTML = getIcon('error') + ' ' + escapeHTML(err.message);
|
||||||
statusEl.style.color = '#ef4444';
|
statusEl.style.color = '#ef4444';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -869,12 +1378,12 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
await API.changeEmail(password, newEmail);
|
await API.changeEmail(password, newEmail);
|
||||||
document.getElementById('changeEmailPassword').value = '';
|
document.getElementById('changeEmailPassword').value = '';
|
||||||
document.getElementById('changeNewEmail').value = '';
|
document.getElementById('changeNewEmail').value = '';
|
||||||
statusEl.textContent = getIcon('success') + ' 邮箱修改成功,正在返回首页…';
|
statusEl.innerHTML = getIcon('success') + ' 邮箱修改成功,正在返回首页…';
|
||||||
statusEl.style.color = '#22c55e';
|
statusEl.style.color = '#22c55e';
|
||||||
// 同上:令牌由服务端补发,保持登录状态。
|
// 同上:令牌由服务端补发,保持登录状态。
|
||||||
setTimeout(() => switchPage('feed'), 800);
|
setTimeout(() => switchPage('feed'), 800);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
statusEl.innerHTML = getIcon('error') + ' ' + escapeHTML(err.message);
|
||||||
statusEl.style.color = '#ef4444';
|
statusEl.style.color = '#ef4444';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -907,21 +1416,26 @@ async function renderSettingsPage(tab = 'profile') {
|
|||||||
const countData = await API.getRecoveryCodesCount();
|
const countData = await API.getRecoveryCodesCount();
|
||||||
if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码';
|
if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('获取恢复码失败:' + err.message);
|
showToast('获取恢复码失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (regenBtn) {
|
if (regenBtn) {
|
||||||
regenBtn.addEventListener('click', async function() {
|
regenBtn.addEventListener('click', async function() {
|
||||||
if (!confirm('重新生成将替换所有旧的恢复码,确定继续吗?')) return;
|
const ok = await showConfirm('重新生成将替换所有旧的恢复码,确定继续吗?', {
|
||||||
|
title: '重新生成恢复码',
|
||||||
|
confirmText: '重新生成',
|
||||||
|
danger: true,
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
try {
|
try {
|
||||||
const data = await API.generateRecoveryCodes();
|
const data = await API.generateRecoveryCodes();
|
||||||
showRecoveryCodesModal(data.codes);
|
showRecoveryCodesModal(data.codes);
|
||||||
const countData = await API.getRecoveryCodesCount();
|
const countData = await API.getRecoveryCodesCount();
|
||||||
if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码';
|
if (recoveryStatus) recoveryStatus.textContent = '剩余 ' + (countData.count || 0) + ' 个可用恢复码';
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('重新生成失败:' + err.message);
|
showToast('重新生成失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -975,7 +1489,7 @@ function openEditModal(postId, currentTitle, currentContent) {
|
|||||||
modal.querySelector('#editPostSaveBtn').addEventListener('click', async function() {
|
modal.querySelector('#editPostSaveBtn').addEventListener('click', async function() {
|
||||||
const title = document.getElementById('editPostTitle').value.trim() || '无标题';
|
const title = document.getElementById('editPostTitle').value.trim() || '无标题';
|
||||||
const content = document.getElementById('editPostContent').value.trim();
|
const content = document.getElementById('editPostContent').value.trim();
|
||||||
if (!content) { alert('请填写内容'); return; }
|
if (!content) { showToast('请填写内容', 'warning'); return; }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await API.updatePost(postId, title, content);
|
await API.updatePost(postId, title, content);
|
||||||
@@ -985,9 +1499,9 @@ function openEditModal(postId, currentTitle, currentContent) {
|
|||||||
} else {
|
} else {
|
||||||
renderFeed();
|
renderFeed();
|
||||||
}
|
}
|
||||||
alert('编辑成功!');
|
showToast('编辑成功!', 'success');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('编辑失败:' + err.message);
|
showToast('编辑失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1042,7 +1556,7 @@ function showRecoveryCodesModal(codes) {
|
|||||||
document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() {
|
document.getElementById('copyRecoveryCodesBtn').addEventListener('click', function() {
|
||||||
const text = codes.join('\n');
|
const text = codes.join('\n');
|
||||||
navigator.clipboard.writeText(text).then(() => {
|
navigator.clipboard.writeText(text).then(() => {
|
||||||
document.getElementById('copyStatus').textContent = getIcon('success') + ' 已复制到剪贴板';
|
document.getElementById('copyStatus').innerHTML = getIcon('success') + ' 已复制到剪贴板';
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
const textarea = document.createElement('textarea');
|
const textarea = document.createElement('textarea');
|
||||||
textarea.value = text;
|
textarea.value = text;
|
||||||
@@ -1050,7 +1564,7 @@ function showRecoveryCodesModal(codes) {
|
|||||||
textarea.select();
|
textarea.select();
|
||||||
document.execCommand('copy');
|
document.execCommand('copy');
|
||||||
textarea.remove();
|
textarea.remove();
|
||||||
document.getElementById('copyStatus').textContent = getIcon('success') + ' 已复制到剪贴板';
|
document.getElementById('copyStatus').innerHTML = getIcon('success') + ' 已复制到剪贴板';
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1135,8 +1649,9 @@ async function init() {
|
|||||||
renderNav();
|
renderNav();
|
||||||
await loadForumName();
|
await loadForumName();
|
||||||
await loadCustomPagesNav();
|
await loadCustomPagesNav();
|
||||||
renderStats();
|
// renderStats / renderLinks 不在此处调用。下面的页面分发中,
|
||||||
renderLinks();
|
// switchPage('feed') 已经会调用它们;若在此处也调一次,
|
||||||
|
// /api/stats 会发出两次请求。
|
||||||
|
|
||||||
const urlParams = new URLSearchParams(window.location.search);
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
const postParam = urlParams.get('post');
|
const postParam = urlParams.get('post');
|
||||||
@@ -1144,6 +1659,13 @@ async function init() {
|
|||||||
const userParam = urlParams.get('user');
|
const userParam = urlParams.get('user');
|
||||||
const postPageParam = urlParams.get('postpage');
|
const postPageParam = urlParams.get('postpage');
|
||||||
const customParam = urlParams.get('custom');
|
const customParam = urlParams.get('custom');
|
||||||
|
const searchParam = urlParams.get('q');
|
||||||
|
|
||||||
|
// 恢复搜索状态:关键词要先于 renderFeed 设定,否则首屏会先按
|
||||||
|
// 普通列表加载一次,再因搜索条件变化重新请求。
|
||||||
|
if (searchParam && window.__feedSearch) {
|
||||||
|
window.__feedSearch.setKeyword(searchParam);
|
||||||
|
}
|
||||||
|
|
||||||
if (postPageParam) {
|
if (postPageParam) {
|
||||||
currentPageNum = parseInt(postPageParam) || 1;
|
currentPageNum = parseInt(postPageParam) || 1;
|
||||||
@@ -1165,6 +1687,14 @@ async function init() {
|
|||||||
switchPage('feed');
|
switchPage('feed');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 直接通过 URL 打开帖子详情或用户主页时,不会经过 switchPage('feed'),
|
||||||
|
// 侧边栏的统计与友链需要在这里补一次。已在 feed 分支内调用过的情形
|
||||||
|
// 通过 currentPage 判断,避免重复请求。
|
||||||
|
if (currentPage !== 'feed') {
|
||||||
|
renderStats();
|
||||||
|
renderLinks();
|
||||||
|
}
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// 绑定所有事件
|
// 绑定所有事件
|
||||||
// ============================================================
|
// ============================================================
|
||||||
@@ -1175,7 +1705,7 @@ async function init() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
toggleTheme(e);
|
toggleTheme(e);
|
||||||
document.getElementById('dropdownMenu').classList.remove('show');
|
closeDropdown(document.getElementById('dropdownMenu'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1184,7 +1714,7 @@ async function init() {
|
|||||||
document.getElementById('dropdownMenu').classList.toggle('show');
|
document.getElementById('dropdownMenu').classList.toggle('show');
|
||||||
});
|
});
|
||||||
document.addEventListener('click', function() {
|
document.addEventListener('click', function() {
|
||||||
document.getElementById('dropdownMenu').classList.remove('show');
|
closeDropdown(document.getElementById('dropdownMenu'));
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('[data-page]').forEach(el => {
|
document.querySelectorAll('[data-page]').forEach(el => {
|
||||||
@@ -1192,22 +1722,23 @@ async function init() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const page = this.dataset.page;
|
const page = this.dataset.page;
|
||||||
if (page === 'admin' && currentUser?.role !== 'admin') {
|
if (page === 'admin' && currentUser?.role !== 'admin') {
|
||||||
alert('无权限访问');
|
showToast('无权限访问', 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
document.getElementById('dropdownMenu').classList.remove('show');
|
closeDropdown(document.getElementById('dropdownMenu'));
|
||||||
switchPage(page);
|
switchPage(page);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.querySelectorAll('.back-btn').forEach(btn => {
|
document.querySelectorAll('.back-btn').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', function() {
|
||||||
switchPage('feed');
|
// 返回按钮等同于后退导航:让当前页向左滑出、首页从下沉状态上浮
|
||||||
|
navigateBackToFeed();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('forumName').addEventListener('click', function() {
|
document.getElementById('forumName').addEventListener('click', function() {
|
||||||
switchPage('feed');
|
navigateBackToFeed();
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== 忘记密码 =====
|
// ===== 忘记密码 =====
|
||||||
@@ -1239,29 +1770,29 @@ async function init() {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await API.resetPassword(email, code, newPassword);
|
await API.resetPassword(email, code, newPassword);
|
||||||
statusEl.textContent = getIcon('success') + ' 重置成功!请登录';
|
statusEl.innerHTML = getIcon('success') + ' 重置成功!请登录';
|
||||||
statusEl.style.color = '#22c55e';
|
statusEl.style.color = '#22c55e';
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
document.getElementById('forgotPasswordModal').classList.remove('active');
|
closeModal(document.getElementById('forgotPasswordModal'));
|
||||||
document.getElementById('resetEmail').value = '';
|
document.getElementById('resetEmail').value = '';
|
||||||
document.getElementById('resetRecoveryCode').value = '';
|
document.getElementById('resetRecoveryCode').value = '';
|
||||||
document.getElementById('resetNewPassword').value = '';
|
document.getElementById('resetNewPassword').value = '';
|
||||||
}, 1500);
|
}, 1500);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
statusEl.textContent = getIcon('error') + ' ' + err.message;
|
statusEl.innerHTML = getIcon('error') + ' ' + escapeHTML(err.message);
|
||||||
statusEl.style.color = '#ef4444';
|
statusEl.style.color = '#ef4444';
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== 发帖 =====
|
// ===== 发帖 =====
|
||||||
document.getElementById('fab').addEventListener('click', () => {
|
document.getElementById('fab').addEventListener('click', () => {
|
||||||
if (!currentUser) { alert('请先登录'); return; }
|
if (!currentUser) { showToast('请先登录', 'warning'); return; }
|
||||||
switchPage('new');
|
switchPage('new');
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById('postSubmit').addEventListener('click', async () => {
|
document.getElementById('postSubmit').addEventListener('click', async () => {
|
||||||
if (!currentUser || !currentUser.id) {
|
if (!currentUser || !currentUser.id) {
|
||||||
alert('请先登录');
|
showToast('请先登录', 'warning');
|
||||||
switchPage('feed');
|
switchPage('feed');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -1269,8 +1800,8 @@ async function init() {
|
|||||||
const content = document.getElementById('postContent').value.trim();
|
const content = document.getElementById('postContent').value.trim();
|
||||||
const captchaInput = document.getElementById('postCaptchaInput').value.trim();
|
const captchaInput = document.getElementById('postCaptchaInput').value.trim();
|
||||||
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
|
const captchaAnswer = parseInt(document.getElementById('postCaptchaInput').dataset.answer);
|
||||||
if (!content) { alert('请填写内容'); return; }
|
if (!content) { showToast('请填写内容', 'warning'); return; }
|
||||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('post'); return; }
|
if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('post'); return; }
|
||||||
const submitButton = document.getElementById('postSubmit');
|
const submitButton = document.getElementById('postSubmit');
|
||||||
submitButton.disabled = true;
|
submitButton.disabled = true;
|
||||||
submitButton.textContent = selectedImageFiles.length ? '上传图片中...' : '发布中...';
|
submitButton.textContent = selectedImageFiles.length ? '上传图片中...' : '发布中...';
|
||||||
@@ -1282,13 +1813,12 @@ async function init() {
|
|||||||
}
|
}
|
||||||
await API.createPost(title, content, images);
|
await API.createPost(title, content, images);
|
||||||
|
|
||||||
alert('发布成功!');
|
showToast('发布成功!', 'success');
|
||||||
clearSelectedImages();
|
clearSelectedImages();
|
||||||
|
// switchPage('feed') 内部已重新渲染列表与统计,无需再调一次
|
||||||
switchPage('feed');
|
switchPage('feed');
|
||||||
renderFeed();
|
|
||||||
renderStats();
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('发布失败:' + err.message);
|
showToast('发布失败:' + err.message, 'error');
|
||||||
} finally {
|
} finally {
|
||||||
submitButton.disabled = false;
|
submitButton.disabled = false;
|
||||||
submitButton.textContent = '发布帖子';
|
submitButton.textContent = '发布帖子';
|
||||||
@@ -1345,28 +1875,36 @@ async function init() {
|
|||||||
const reason = document.getElementById('reportReason').value;
|
const reason = document.getElementById('reportReason').value;
|
||||||
try {
|
try {
|
||||||
await API.createReport(reportTargetPostId, reason);
|
await API.createReport(reportTargetPostId, reason);
|
||||||
document.getElementById('reportModal').classList.remove('active');
|
closeModal(document.getElementById('reportModal'));
|
||||||
alert('举报已提交,管理员将尽快处理');
|
showToast('举报已提交,管理员将尽快处理', 'success');
|
||||||
reportTargetPostId = null;
|
reportTargetPostId = null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('举报失败:' + err.message);
|
showToast('举报失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== 模态框关闭 =====
|
// ===== 模态框关闭 =====
|
||||||
document.querySelectorAll('.modal .close').forEach(btn => {
|
document.querySelectorAll('.modal .close').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', function() {
|
||||||
document.getElementById(this.dataset.modal).classList.remove('active');
|
closeModal(document.getElementById(this.dataset.modal));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
document.querySelectorAll('.modal').forEach(m => {
|
document.querySelectorAll('.modal').forEach(m => {
|
||||||
m.addEventListener('click', function(e) {
|
m.addEventListener('click', function(e) {
|
||||||
if (e.target === this) this.classList.remove('active');
|
if (e.target === this) closeModal(this);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== 前进后退 =====
|
// ===== 前进后退 =====
|
||||||
|
// popstate 由浏览器前进/后退触发。这类切换用反向滑入动画,
|
||||||
|
// 与主动点击进入页面区分开,让用户感知到「我是往回走的」。
|
||||||
|
let navigatingBack = false;
|
||||||
window.addEventListener('popstate', function(e) {
|
window.addEventListener('popstate', function(e) {
|
||||||
|
navigatingBack = true;
|
||||||
|
// 标记只对紧接着的一次切换生效,渲染完成后立即清除,
|
||||||
|
// 避免影响后续的主动跳转。
|
||||||
|
setTimeout(() => { navigatingBack = false; }, 0);
|
||||||
|
|
||||||
const state = e.state || {};
|
const state = e.state || {};
|
||||||
const page = state.page || 'feed';
|
const page = state.page || 'feed';
|
||||||
const postId = state.postId || null;
|
const postId = state.postId || null;
|
||||||
@@ -1383,6 +1921,9 @@ async function init() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 供各页面切换函数查询当前是否为后退导航
|
||||||
|
window.isNavigatingBack = () => navigatingBack;
|
||||||
|
|
||||||
// ===== 私信按钮 =====
|
// ===== 私信按钮 =====
|
||||||
const messageBtn = document.getElementById('messageBtn');
|
const messageBtn = document.getElementById('messageBtn');
|
||||||
if (messageBtn) {
|
if (messageBtn) {
|
||||||
@@ -1390,7 +1931,7 @@ async function init() {
|
|||||||
messageBtn.parentNode.replaceChild(newBtn, messageBtn);
|
messageBtn.parentNode.replaceChild(newBtn, messageBtn);
|
||||||
newBtn.addEventListener('click', function(e) {
|
newBtn.addEventListener('click', function(e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (!currentUser) { alert('请先登录'); return; }
|
if (!currentUser) { showToast('请先登录', 'warning'); return; }
|
||||||
openMessageList();
|
openMessageList();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1418,7 +1959,7 @@ async function init() {
|
|||||||
document.querySelectorAll('.modal').forEach(m => {
|
document.querySelectorAll('.modal').forEach(m => {
|
||||||
m.addEventListener('click', function(e) {
|
m.addEventListener('click', function(e) {
|
||||||
if (e.target === this) {
|
if (e.target === this) {
|
||||||
this.classList.remove('active');
|
closeModal(this);
|
||||||
if (this.id === 'messageListModal') {
|
if (this.id === 'messageListModal') {
|
||||||
closeMessageList();
|
closeMessageList();
|
||||||
}
|
}
|
||||||
|
|||||||
+111
-14
@@ -2,6 +2,16 @@
|
|||||||
// 🔐 认证
|
// 🔐 认证
|
||||||
// ============================================================
|
// ============================================================
|
||||||
|
|
||||||
|
// 三个认证表单的提交拦截。
|
||||||
|
// 输入框与按钮原本裸放在 div 中(页面没有 form 标签),密码管理器因此
|
||||||
|
// 找不到表单边界,会靠启发式猜测把首页搜索框也当成账号字段填入。
|
||||||
|
// 现改用真正的 <form> 包裹,需要拦下默认提交行为——否则按回车或点按钮
|
||||||
|
// 会触发浏览器原生提交导致页面刷新。
|
||||||
|
['loginForm', 'registerForm', 'forgotPasswordForm'].forEach(id => {
|
||||||
|
const form = document.getElementById(id);
|
||||||
|
if (form) form.addEventListener('submit', e => e.preventDefault());
|
||||||
|
});
|
||||||
|
|
||||||
// 登录事件绑定
|
// 登录事件绑定
|
||||||
document.getElementById('loginBtn').addEventListener('click', () => {
|
document.getElementById('loginBtn').addEventListener('click', () => {
|
||||||
document.getElementById('loginModal').classList.add('active');
|
document.getElementById('loginModal').classList.add('active');
|
||||||
@@ -10,10 +20,10 @@ document.getElementById('loginBtn').addEventListener('click', () => {
|
|||||||
document.getElementById('loginSubmit').addEventListener('click', async () => {
|
document.getElementById('loginSubmit').addEventListener('click', async () => {
|
||||||
const email = document.getElementById('loginEmail').value.trim();
|
const email = document.getElementById('loginEmail').value.trim();
|
||||||
const password = document.getElementById('loginPassword').value;
|
const password = document.getElementById('loginPassword').value;
|
||||||
if (!email || !password) { alert('请填写完整信息'); return; }
|
if (!email || !password) { showToast('请填写完整信息', 'warning'); return; }
|
||||||
try {
|
try {
|
||||||
const result = await API.login(email, password);
|
const result = await API.login(email, password);
|
||||||
document.getElementById('loginModal').classList.remove('active');
|
closeModal(document.getElementById('loginModal'));
|
||||||
document.getElementById('loginEmail').value = '';
|
document.getElementById('loginEmail').value = '';
|
||||||
document.getElementById('loginPassword').value = '';
|
document.getElementById('loginPassword').value = '';
|
||||||
if (result.user) {
|
if (result.user) {
|
||||||
@@ -27,38 +37,122 @@ document.getElementById('loginSubmit').addEventListener('click', async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('登录失败:' + err.message);
|
showToast('登录失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 注册事件绑定
|
// 注册事件绑定
|
||||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||||
refreshCaptcha('reg');
|
refreshCaptcha('reg');
|
||||||
|
syncBootstrapTokenField();
|
||||||
|
syncEmailCodeField();
|
||||||
document.getElementById('registerModal').classList.add('active');
|
document.getElementById('registerModal').classList.add('active');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 邮箱验证码字段:仅在站点开启邮箱验证且 SMTP 可用时显示。
|
||||||
|
// 显隐通过切换类名完成,布局交给 CSS——直接改 style.display 会覆盖
|
||||||
|
// 掉保证输入框与按钮并排的 flex 布局。
|
||||||
|
async function syncEmailCodeField() {
|
||||||
|
const row = document.getElementById('regEmailCodeRow');
|
||||||
|
const field = document.getElementById('regEmailCode');
|
||||||
|
if (!row || !field) return;
|
||||||
|
try {
|
||||||
|
const settings = await API.getSettings();
|
||||||
|
const required = settings.email_verify_required === true;
|
||||||
|
row.classList.toggle('is-visible', required);
|
||||||
|
if (!required) field.value = '';
|
||||||
|
} catch (err) {
|
||||||
|
// 取不到设置时按「不需要」处理,避免用户卡在无法完成的注册流程上
|
||||||
|
row.classList.remove('is-visible');
|
||||||
|
field.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送邮箱验证码,含 60 秒倒计时防止连点
|
||||||
|
(function bindSendCodeButton() {
|
||||||
|
const btn = document.getElementById('regSendCodeBtn');
|
||||||
|
if (!btn) return;
|
||||||
|
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
const email = document.getElementById('regEmail').value.trim();
|
||||||
|
if (!email) { showToast('请先填写邮箱', 'warning'); return; }
|
||||||
|
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
await API.sendRegisterCode(email);
|
||||||
|
showToast('验证码已发送,请查收邮件', 'success');
|
||||||
|
|
||||||
|
let remain = 60;
|
||||||
|
btn.textContent = remain + 's';
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
remain -= 1;
|
||||||
|
if (remain <= 0) {
|
||||||
|
clearInterval(timer);
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '获取验证码';
|
||||||
|
} else {
|
||||||
|
btn.textContent = remain + 's';
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
} catch (err) {
|
||||||
|
btn.disabled = false;
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})();
|
||||||
|
|
||||||
|
// 管理员初始化令牌输入框仅在首次部署且配置了引导令牌时出现。
|
||||||
|
// 其余情况(普通部署、已初始化完成)普通用户完全看不到它。
|
||||||
|
async function syncBootstrapTokenField() {
|
||||||
|
const field = document.getElementById('regBootstrapToken');
|
||||||
|
if (!field) return;
|
||||||
|
try {
|
||||||
|
const settings = await API.getSettings();
|
||||||
|
const required = settings.bootstrap_required === true;
|
||||||
|
field.style.display = required ? '' : 'none';
|
||||||
|
if (!required) field.value = '';
|
||||||
|
} catch (err) {
|
||||||
|
// 取不到设置时按「不需要」处理,避免把内部机制暴露给普通用户。
|
||||||
|
field.style.display = 'none';
|
||||||
|
field.value = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
document.getElementById('registerSubmit').addEventListener('click', async () => {
|
document.getElementById('registerSubmit').addEventListener('click', async () => {
|
||||||
const username = document.getElementById('regUsername').value.trim();
|
const username = document.getElementById('regUsername').value.trim();
|
||||||
const email = document.getElementById('regEmail').value.trim();
|
const email = document.getElementById('regEmail').value.trim();
|
||||||
const password = document.getElementById('regPassword').value;
|
const password = document.getElementById('regPassword').value;
|
||||||
const bootstrapToken = document.getElementById('regBootstrapToken').value.trim();
|
const bootstrapField = document.getElementById('regBootstrapToken');
|
||||||
|
// 字段被隐藏时视为未提供,避免普通注册误传空串触发后端的令牌校验分支。
|
||||||
|
const bootstrapToken = bootstrapField && bootstrapField.style.display !== 'none'
|
||||||
|
? bootstrapField.value.trim()
|
||||||
|
: '';
|
||||||
|
const codeField = document.getElementById('regEmailCode');
|
||||||
|
const codeRow = document.getElementById('regEmailCodeRow');
|
||||||
|
// 以容器的 is-visible 类判断该字段是否启用,而不是读 style.display
|
||||||
|
const codeEnabled = Boolean(codeRow && codeRow.classList.contains('is-visible'));
|
||||||
|
const emailCode = codeEnabled && codeField ? codeField.value.trim() : '';
|
||||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||||
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
if (!username || !email || !password) { showToast('请填写完整信息', 'warning'); return; }
|
||||||
if (password.length < 6) { alert('密码至少6位'); return; }
|
if (password.length < 6) { showToast('密码至少6位', 'warning'); return; }
|
||||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
if (codeEnabled && !emailCode) {
|
||||||
|
showToast('请输入邮箱验证码', 'warning'); return;
|
||||||
|
}
|
||||||
|
if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('reg'); return; }
|
||||||
try {
|
try {
|
||||||
await API.register(email, password, username, bootstrapToken);
|
await API.register(email, password, username, bootstrapToken, emailCode);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('注册失败:' + err.message);
|
showToast('注册失败:' + err.message, 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('registerModal').classList.remove('active');
|
closeModal(document.getElementById('registerModal'));
|
||||||
document.getElementById('regUsername').value = '';
|
document.getElementById('regUsername').value = '';
|
||||||
document.getElementById('regEmail').value = '';
|
document.getElementById('regEmail').value = '';
|
||||||
document.getElementById('regPassword').value = '';
|
document.getElementById('regPassword').value = '';
|
||||||
document.getElementById('regBootstrapToken').value = '';
|
if (bootstrapField) bootstrapField.value = '';
|
||||||
|
if (codeField) codeField.value = '';
|
||||||
document.getElementById('regCaptchaInput').value = '';
|
document.getElementById('regCaptchaInput').value = '';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -73,7 +167,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
|||||||
renderStats();
|
renderStats();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('注册成功,但自动登录失败,请手动登录:' + err.message);
|
showToast('注册成功,但自动登录失败,请手动登录:' + err.message, 'error');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,7 +178,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('恢复码生成失败:', err);
|
console.warn('恢复码生成失败:', err);
|
||||||
alert('注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。');
|
showToast('注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。', 'error');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -94,7 +188,10 @@ document.getElementById('regCaptchaQuestion').addEventListener('click', function
|
|||||||
|
|
||||||
// 退出
|
// 退出
|
||||||
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
document.getElementById('logoutBtn').addEventListener('click', async () => {
|
||||||
if (!confirm('确定要退出吗?')) return;
|
const ok = await showConfirm('确定要退出吗?', {
|
||||||
|
title: '退出登录', confirmText: '退出',
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
await API.logout();
|
await API.logout();
|
||||||
currentUser = null;
|
currentUser = null;
|
||||||
renderNav();
|
renderNav();
|
||||||
|
|||||||
+154
-44
@@ -6,18 +6,52 @@ let currentSort = 'latest';
|
|||||||
let totalPages = 1;
|
let totalPages = 1;
|
||||||
const PAGE_SIZE = 20;
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
|
// 当前搜索关键词。为空表示处于普通列表模式。
|
||||||
|
let currentSearch = '';
|
||||||
|
|
||||||
|
// 翻页后滚回列表顶部。分页控件在列表末尾,不回到顶部的话用户看到的
|
||||||
|
// 仍是新一页的底部。
|
||||||
|
// 尊重系统的「减少动画」设置:开启时直接跳转,不做平滑滚动。
|
||||||
|
function scrollFeedToTop() {
|
||||||
|
const reduceMotion = window.matchMedia &&
|
||||||
|
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||||
|
window.scrollTo({
|
||||||
|
top: 0,
|
||||||
|
behavior: reduceMotion ? 'auto' : 'smooth',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function renderFeed() {
|
function renderFeed() {
|
||||||
const container = document.getElementById('postList');
|
const container = document.getElementById('postList');
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
const keyword = currentSearch;
|
||||||
API.getPosts(currentSort, currentPageNum, PAGE_SIZE).then(result => {
|
|
||||||
|
// 骨架屏只在首次加载时显示。翻页时列表已有内容,再画一遍骨架会
|
||||||
|
// 造成明显的闪动,反而比直接留白更糟。
|
||||||
|
const isFirstLoad = container.dataset.loaded !== '1';
|
||||||
|
container.innerHTML = isFirstLoad
|
||||||
|
? Skeleton.postList(3)
|
||||||
|
: '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
||||||
|
|
||||||
|
const request = keyword
|
||||||
|
? API.searchPosts(keyword, currentPageNum, PAGE_SIZE)
|
||||||
|
: API.getPosts(currentSort, currentPageNum, PAGE_SIZE);
|
||||||
|
|
||||||
|
request.then(result => {
|
||||||
|
container.dataset.loaded = '1';
|
||||||
const posts = result.data || [];
|
const posts = result.data || [];
|
||||||
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
|
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
|
||||||
totalPages = pagination.totalPages || 1;
|
totalPages = pagination.totalPages || 1;
|
||||||
currentPageNum = pagination.page || 1;
|
currentPageNum = pagination.page || 1;
|
||||||
|
|
||||||
if (posts.length === 0 && currentPageNum === 1) {
|
if (posts.length === 0 && currentPageNum === 1) {
|
||||||
container.innerHTML =
|
// 空结果提示。关键词单独放在 <strong> 里,让固定文案能作为独立
|
||||||
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
|
// 文本节点被 i18n 匹配到——整句含动态关键词时匹配不上词典。
|
||||||
|
container.innerHTML = keyword
|
||||||
|
? '<div class="search-empty">'
|
||||||
|
+ '<span>没有找到相关帖子</span><br>'
|
||||||
|
+ '<strong>「' + escapeHTML(keyword) + '」</strong><br>'
|
||||||
|
+ '<span style="font-size:13px;">试试其他关键词,或检查是否有错别字</span></div>'
|
||||||
|
: '<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,12 +68,23 @@ function renderFeed() {
|
|||||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
|
'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) +
|
||||||
'&background=6366f1&color=fff&size=64';
|
'&background=6366f1&color=fff&size=64';
|
||||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||||
|
// 列表里最多展示 3 张图,其余折叠为「+N」。
|
||||||
|
// 附件上限是 6 张,若全部铺开会把卡片撑得很高,且与相邻卡片不齐。
|
||||||
let imagesHtml = '';
|
let imagesHtml = '';
|
||||||
if (p.images && p.images.length > 0) {
|
if (p.images && p.images.length > 0) {
|
||||||
|
const MAX_THUMBS = 3;
|
||||||
|
const shown = p.images.slice(0, MAX_THUMBS);
|
||||||
|
const rest = p.images.length - shown.length;
|
||||||
|
|
||||||
imagesHtml = '<div class="post-images">';
|
imagesHtml = '<div class="post-images">';
|
||||||
p.images.forEach(img => {
|
shown.forEach(img => {
|
||||||
imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) + '" class="post-image" style="cursor:pointer;" />';
|
imagesHtml += '<img src="' + escapeHTML(safeURL(img, { image: true })) +
|
||||||
|
'" class="post-image" style="cursor:pointer;" />';
|
||||||
});
|
});
|
||||||
|
// 多于 3 张时,在末张右下角叠加剩余数量
|
||||||
|
if (rest > 0) {
|
||||||
|
imagesHtml += '<span class="post-image-more">+' + rest + '</span>';
|
||||||
|
}
|
||||||
imagesHtml += '</div>';
|
imagesHtml += '</div>';
|
||||||
}
|
}
|
||||||
const replyCount = p.reply_count || 0;
|
const replyCount = p.reply_count || 0;
|
||||||
@@ -51,7 +96,7 @@ function renderFeed() {
|
|||||||
if (p.signature) {
|
if (p.signature) {
|
||||||
const sigContent = renderMarkdown(p.signature);
|
const sigContent = renderMarkdown(p.signature);
|
||||||
signatureHtml = `
|
signatureHtml = `
|
||||||
<div style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
<div class="post-signature" style="margin-top:10px;padding-top:8px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||||
${sigContent}
|
${sigContent}
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
@@ -72,16 +117,8 @@ function renderFeed() {
|
|||||||
<div class="post-actions">
|
<div class="post-actions">
|
||||||
<span>
|
<span>
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||||
${replyCount}
|
${replyCount} 条回复
|
||||||
</span>
|
</span>
|
||||||
<button class="action-report" data-postid="${p.id}">
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
|
||||||
举报
|
|
||||||
</button>
|
|
||||||
${currentUser && currentUser.id === p.user_id ? `<button class="action-delete" data-postid="${p.id}">
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
|
||||||
删除
|
|
||||||
</button>` : ''}
|
|
||||||
</div>
|
</div>
|
||||||
${signatureHtml}
|
${signatureHtml}
|
||||||
</div>
|
</div>
|
||||||
@@ -143,7 +180,10 @@ function renderFeed() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
container.innerHTML += paginationHtml;
|
// 用 insertAdjacentHTML 追加而非 innerHTML +=:
|
||||||
|
// 后者会让浏览器重新解析整个容器,导致已渲染的帖子卡片被重建,
|
||||||
|
// 入场动画会重放一遍,视觉上像闪了一下。
|
||||||
|
container.insertAdjacentHTML('beforeend', paginationHtml);
|
||||||
|
|
||||||
container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => {
|
container.querySelectorAll('.page-btn:not([disabled])').forEach(btn => {
|
||||||
btn.addEventListener('click', function() {
|
btn.addEventListener('click', function() {
|
||||||
@@ -154,6 +194,9 @@ function renderFeed() {
|
|||||||
url.searchParams.set('postpage', page);
|
url.searchParams.set('postpage', page);
|
||||||
window.history.pushState({}, '', url);
|
window.history.pushState({}, '', url);
|
||||||
renderFeed();
|
renderFeed();
|
||||||
|
// 分页控件位于列表末尾,翻页后若不回到顶部,用户看到的仍是
|
||||||
|
// 新一页的底部,需要手动上滚才能读到第一条。这里平滑滚回顶部。
|
||||||
|
scrollFeedToTop();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -181,39 +224,19 @@ function renderFeed() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
container.querySelectorAll('.action-report').forEach(btn => {
|
// 卡片上不再放举报与删除按钮:这两个操作针对的是帖子内容本身,
|
||||||
btn.addEventListener('click', function(e) {
|
// 放在卡片上容易被误解为对整张卡片操作,也容易误点。
|
||||||
e.stopPropagation();
|
// 它们统一放在帖子详情页,用户点进帖子后操作。
|
||||||
if (!currentUser) { alert('请先登录'); return; }
|
// (卡片的点击跳转绑定在上方,此处无需重复绑定。)
|
||||||
reportTargetPostId = this.dataset.postid;
|
|
||||||
document.getElementById('reportModal').classList.add('active');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
container.querySelectorAll('.action-delete').forEach(btn => {
|
|
||||||
btn.addEventListener('click', function(e) {
|
|
||||||
e.stopPropagation();
|
|
||||||
if (confirm('确定要删除这条帖子吗?')) {
|
|
||||||
API.deletePost(this.dataset.postid).then(() => {
|
|
||||||
renderFeed();
|
|
||||||
renderStats();
|
|
||||||
}).catch(err => alert('删除失败:' + err.message));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
|
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) +
|
||||||
'</div>';
|
'</div>';
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderStats() {
|
// 注:renderStats 定义在 app.js 中(同时更新主页与帖子详情页的统计,
|
||||||
API.getStats().then(stats => {
|
// 且带空值保护)。此处原先有一份同名实现,因 app.js 后加载而被整体
|
||||||
document.getElementById('statTopics').textContent = stats.topics || 0;
|
// 覆盖,属于死代码,已删除以免日后改错地方。
|
||||||
document.getElementById('statPosts').textContent = stats.posts || 0;
|
|
||||||
document.getElementById('statUsers').textContent = stats.users || 0;
|
|
||||||
// 在线人数已移除
|
|
||||||
}).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderLinks() {
|
function renderLinks() {
|
||||||
API.getLinks().then(links => {
|
API.getLinks().then(links => {
|
||||||
@@ -243,3 +266,90 @@ document.querySelectorAll('.tab').forEach(tab => {
|
|||||||
renderFeed();
|
renderFeed();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 🔍 搜索
|
||||||
|
// ============================================================
|
||||||
|
// 输入时防抖 350ms 自动搜索,回车立即搜索。
|
||||||
|
// 关键词写入 URL(?q=),刷新与分享可保持搜索状态。
|
||||||
|
|
||||||
|
(function initSearch() {
|
||||||
|
const input = document.getElementById('postSearchInput');
|
||||||
|
const clearBtn = document.getElementById('postSearchClear');
|
||||||
|
const wrap = input ? input.closest('.feed-search') : null;
|
||||||
|
if (!input) return;
|
||||||
|
|
||||||
|
let debounceTimer = null;
|
||||||
|
|
||||||
|
function syncClearButton() {
|
||||||
|
if (clearBtn) clearBtn.style.display = input.value.trim() ? 'flex' : 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
function runSearch(keyword, { updateUrl = true } = {}) {
|
||||||
|
const next = (keyword || '').trim();
|
||||||
|
// 与当前状态相同则不必重新请求
|
||||||
|
if (next === currentSearch && currentPageNum === 1) return;
|
||||||
|
|
||||||
|
currentSearch = next;
|
||||||
|
currentPageNum = 1;
|
||||||
|
|
||||||
|
if (updateUrl) {
|
||||||
|
const url = new URL(window.location);
|
||||||
|
if (next) url.searchParams.set('q', next);
|
||||||
|
else url.searchParams.delete('q');
|
||||||
|
url.searchParams.delete('postpage');
|
||||||
|
window.history.pushState({}, '', url);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wrap) wrap.classList.add('is-searching');
|
||||||
|
renderFeed();
|
||||||
|
// renderFeed 内部是异步的,这里在下一轮事件循环后移除进度条即可
|
||||||
|
// (列表本身会先显示「加载中」,不会长时间空白)
|
||||||
|
window.setTimeout(() => {
|
||||||
|
if (wrap) wrap.classList.remove('is-searching');
|
||||||
|
}, 600);
|
||||||
|
}
|
||||||
|
|
||||||
|
input.addEventListener('input', () => {
|
||||||
|
syncClearButton();
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
debounceTimer = setTimeout(() => runSearch(input.value), 350);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回车立即搜索,跳过防抖
|
||||||
|
input.addEventListener('keydown', e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
runSearch(input.value);
|
||||||
|
} else if (e.key === 'Escape') {
|
||||||
|
e.preventDefault();
|
||||||
|
input.value = '';
|
||||||
|
syncClearButton();
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
runSearch('');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (clearBtn) {
|
||||||
|
clearBtn.addEventListener('click', () => {
|
||||||
|
input.value = '';
|
||||||
|
syncClearButton();
|
||||||
|
if (debounceTimer) clearTimeout(debounceTimer);
|
||||||
|
runSearch('');
|
||||||
|
input.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 暴露给外部(初始化时按 URL 恢复搜索状态)
|
||||||
|
window.__feedSearch = {
|
||||||
|
setKeyword(keyword) {
|
||||||
|
input.value = keyword || '';
|
||||||
|
currentSearch = (keyword || '').trim();
|
||||||
|
syncClearButton();
|
||||||
|
},
|
||||||
|
run: runSearch,
|
||||||
|
};
|
||||||
|
|
||||||
|
syncClearButton();
|
||||||
|
})();
|
||||||
+335
-1
@@ -278,6 +278,173 @@ const TRANSLATIONS = {
|
|||||||
|
|
||||||
// ===== 论坛名称 =====
|
// ===== 论坛名称 =====
|
||||||
'论坛名称': '论坛名称',
|
'论坛名称': '论坛名称',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:操作状态与错误提示 =====
|
||||||
|
// 源码里这些提示多带「:」后缀拼接具体原因,与上方不带冒号的
|
||||||
|
// 短词是不同字符串,必须分别登记才能命中。
|
||||||
|
'保存失败:': '保存失败:',
|
||||||
|
'编辑成功!': '编辑成功!',
|
||||||
|
'编辑失败:': '编辑失败:',
|
||||||
|
'操作失败:': '操作失败:',
|
||||||
|
'打开私信失败:': '打开私信失败:',
|
||||||
|
'登录失败:': '登录失败:',
|
||||||
|
'发布失败:': '发布失败:',
|
||||||
|
'发送失败:': '发送失败:',
|
||||||
|
'恢复码生成失败:': '恢复码生成失败:',
|
||||||
|
'回复失败:': '回复失败:',
|
||||||
|
'获取恢复码失败:': '获取恢复码失败:',
|
||||||
|
'举报失败:': '举报失败:',
|
||||||
|
'删除失败:': '删除失败:',
|
||||||
|
'上传失败:': '上传失败:',
|
||||||
|
'添加失败:': '添加失败:',
|
||||||
|
'重新生成失败:': '重新生成失败:',
|
||||||
|
'注册失败:': '注册失败:',
|
||||||
|
'页面加载失败:': '页面加载失败:',
|
||||||
|
'加载失败:': '加载失败:',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:表单校验与按钮 =====
|
||||||
|
'保存修改': '保存修改',
|
||||||
|
'密码至少6位': '密码至少6位',
|
||||||
|
'新密码至少6位': '新密码至少6位',
|
||||||
|
'验证码错误,请重新计算': '验证码错误,请重新计算',
|
||||||
|
'用户名不能为空': '用户名不能为空',
|
||||||
|
'请输入论坛名称': '请输入论坛名称',
|
||||||
|
'请填写回复内容': '请填写回复内容',
|
||||||
|
'页面名称只允许字母、数字、短横线和下划线': '页面名称只允许字母、数字、短横线和下划线',
|
||||||
|
'移除': '移除',
|
||||||
|
'名称': '名称',
|
||||||
|
'图片': '图片',
|
||||||
|
'未知': '未知',
|
||||||
|
'系统': '系统',
|
||||||
|
'无权限访问': '无权限访问',
|
||||||
|
'匿名用户': '匿名用户',
|
||||||
|
'发布中...': '发布中...',
|
||||||
|
'上传图片中...': '上传图片中...',
|
||||||
|
'松开上传': '松开上传',
|
||||||
|
'每篇帖子最多上传 6 张图片': '每篇帖子最多上传 6 张图片',
|
||||||
|
'上传响应无效': '上传响应无效',
|
||||||
|
'图片上传失败': '图片上传失败',
|
||||||
|
'已选择:': '已选择:',
|
||||||
|
'举报不成立': '举报不成立',
|
||||||
|
'已删除违规帖子': '已删除违规帖子',
|
||||||
|
'暂无用户': '暂无用户',
|
||||||
|
'暂无友情链接': '暂无友情链接',
|
||||||
|
'暂无消息': '暂无消息',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:确认对话框 =====
|
||||||
|
'确定要': '确定要',
|
||||||
|
'置顶吗?': '置顶吗?',
|
||||||
|
'确定要退出吗?': '确定要退出吗?',
|
||||||
|
'确定删除该链接吗?': '确定删除该链接吗?',
|
||||||
|
'确定要删除这条回复吗?': '确定要删除这条回复吗?',
|
||||||
|
'确定要删除这条帖子吗?': '确定要删除这条帖子吗?',
|
||||||
|
'确定要删除这个页面吗?': '确定要删除这个页面吗?',
|
||||||
|
'确定要删除该帖子并标记举报为已处理吗?': '确定要删除该帖子并标记举报为已处理吗?',
|
||||||
|
'确定要删除自定义 CSS 吗?将恢复默认样式。': '确定要删除自定义 CSS 吗?将恢复默认样式。',
|
||||||
|
'重新生成将替换所有旧的恢复码,确定继续吗?': '重新生成将替换所有旧的恢复码,确定继续吗?',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:混合文案 =====
|
||||||
|
'当有人回复你的帖子或处理你的举报时,会在这里通知你': '当有人回复你的帖子或处理你的举报时,会在这里通知你',
|
||||||
|
'举报已提交,管理员将尽快处理': '举报已提交,管理员将尽快处理',
|
||||||
|
'注册成功,但自动登录失败,请手动登录:': '注册成功,但自动登录失败,请手动登录:',
|
||||||
|
'注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。': '注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。',
|
||||||
|
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': '支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染',
|
||||||
|
|
||||||
|
// ===== 动态文本前缀 =====
|
||||||
|
// 「剩余 N 个可用恢复码」由模板字符串生成,整串无法匹配,
|
||||||
|
// 因此登记可命中的固定片段。
|
||||||
|
'剩余': '剩余',
|
||||||
|
'个可用恢复码': '个可用恢复码',
|
||||||
|
'原因:': '原因:',
|
||||||
|
'状态:': '状态:',
|
||||||
|
'处理人:': '处理人:',
|
||||||
|
'帖子:': '帖子:',
|
||||||
|
|
||||||
|
// ===== 确认对话框 =====
|
||||||
|
// showConfirm() 动态创建 DOM,i18n 的 MutationObserver 会翻译其
|
||||||
|
// 文本节点,但这些文案必须先在词典登记才能命中。
|
||||||
|
'请确认': '请确认',
|
||||||
|
'确定': '确定',
|
||||||
|
'删除回复': '删除回复',
|
||||||
|
'删除友链': '删除友链',
|
||||||
|
'删除页面': '删除页面',
|
||||||
|
'修改用户角色': '修改用户角色',
|
||||||
|
'重新生成恢复码': '重新生成恢复码',
|
||||||
|
'退出登录': '退出登录',
|
||||||
|
|
||||||
|
// ===== 用户屏蔽 =====
|
||||||
|
'屏蔽': '屏蔽',
|
||||||
|
'解除屏蔽': '解除屏蔽',
|
||||||
|
'已屏蔽': '已屏蔽',
|
||||||
|
'会话': '会话',
|
||||||
|
'屏蔽用户': '屏蔽用户',
|
||||||
|
'已屏蔽该用户': '已屏蔽该用户',
|
||||||
|
'已解除屏蔽': '已解除屏蔽',
|
||||||
|
'还没有屏蔽任何人': '还没有屏蔽任何人',
|
||||||
|
'加载中…': '加载中…',
|
||||||
|
'加载失败': '加载失败',
|
||||||
|
|
||||||
|
// ===== 私信用户搜索 =====
|
||||||
|
'搜索用户名开始私信…': '搜索用户名开始私信…',
|
||||||
|
'搜索用户': '搜索用户',
|
||||||
|
'没有找到匹配的用户': '没有找到匹配的用户',
|
||||||
|
'点击发送私信': '点击发送私信',
|
||||||
|
'对方回复前还可发送': '对方回复前还可发送',
|
||||||
|
'条消息': '条消息',
|
||||||
|
'对方回复前无法继续发送,请等待对方回复': '对方回复前无法继续发送,请等待对方回复',
|
||||||
|
'搜索中…': '搜索中…',
|
||||||
|
'搜索失败:': '搜索失败:',
|
||||||
|
|
||||||
|
// ===== 帖子搜索 =====
|
||||||
|
'搜索帖子…': '搜索帖子…',
|
||||||
|
'清除搜索': '清除搜索',
|
||||||
|
'请输入搜索关键词': '请输入搜索关键词',
|
||||||
|
'搜索关键词过长(最多 100 字)': '搜索关键词过长(最多 100 字)',
|
||||||
|
'没有找到相关帖子': '没有找到相关帖子',
|
||||||
|
'试试其他关键词,或检查是否有错别字': '试试其他关键词,或检查是否有错别字',
|
||||||
|
|
||||||
|
// ===== SMTP 与邮箱验证 =====
|
||||||
|
'邮件设置': '邮件设置',
|
||||||
|
'启用邮件发送': '启用邮件发送',
|
||||||
|
'SMTP 服务器': 'SMTP 服务器',
|
||||||
|
'端口': '端口',
|
||||||
|
'加密方式': '加密方式',
|
||||||
|
'密码 / 授权码': '密码 / 授权码',
|
||||||
|
'发件人名称': '发件人名称',
|
||||||
|
'发件人邮箱': '发件人邮箱',
|
||||||
|
'保存配置': '保存配置',
|
||||||
|
'发送测试邮件': '发送测试邮件',
|
||||||
|
'清除密码': '清除密码',
|
||||||
|
'注册邮箱验证': '注册邮箱验证',
|
||||||
|
'要求注册时验证邮箱': '要求注册时验证邮箱',
|
||||||
|
'获取验证码': '获取验证码',
|
||||||
|
'邮箱验证码': '邮箱验证码',
|
||||||
|
'配置完整,可以发信': '配置完整,可以发信',
|
||||||
|
'尚未配置完成,邮件功能不可用': '尚未配置完成,邮件功能不可用',
|
||||||
|
'验证码已发送,请查收邮件': '验证码已发送,请查收邮件',
|
||||||
|
'请输入邮箱验证码': '请输入邮箱验证码',
|
||||||
|
'请输入有效邮箱': '请输入有效邮箱',
|
||||||
|
'该邮箱已被注册': '该邮箱已被注册',
|
||||||
|
'本站未开启邮箱验证': '本站未开启邮箱验证',
|
||||||
|
'请先获取验证码': '请先获取验证码',
|
||||||
|
'验证码已过期,请重新获取': '验证码已过期,请重新获取',
|
||||||
|
'尝试次数过多,请重新获取验证码': '尝试次数过多,请重新获取验证码',
|
||||||
|
'验证码错误': '验证码错误',
|
||||||
|
'配置已保存': '配置已保存',
|
||||||
|
'密码已清除': '密码已清除',
|
||||||
|
'已开启注册邮箱验证': '已开启注册邮箱验证',
|
||||||
|
'已关闭注册邮箱验证': '已关闭注册邮箱验证',
|
||||||
|
'加载配置失败:': '加载配置失败:',
|
||||||
|
'已保存密码,留空则不修改': '已保存密码,留空则不修改',
|
||||||
|
'尚未设置密码': '尚未设置密码',
|
||||||
|
'留空表示不修改已保存的密码': '留空表示不修改已保存的密码',
|
||||||
|
'通常为完整邮箱地址': '通常为完整邮箱地址',
|
||||||
|
'例如:论坛名称': '例如:论坛名称',
|
||||||
|
'注册验证码': '注册验证码',
|
||||||
|
'密码重置验证码': '密码重置验证码',
|
||||||
|
'Forumlify SMTP 测试邮件': 'Forumlify SMTP 测试邮件',
|
||||||
|
'允许自签证书(仅自建邮件服务器需要)': '允许自签证书(仅自建邮件服务器需要)',
|
||||||
|
'必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。': '必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。',
|
||||||
},
|
},
|
||||||
|
|
||||||
'en': {
|
'en': {
|
||||||
@@ -504,7 +671,10 @@ const TRANSLATIONS = {
|
|||||||
'用户不存在': 'User not found',
|
'用户不存在': 'User not found',
|
||||||
'这个人很懒,什么都没写': 'This user is lazy, nothing written',
|
'这个人很懒,什么都没写': 'This user is lazy, nothing written',
|
||||||
'加入': 'Joined',
|
'加入': 'Joined',
|
||||||
'于': '',
|
// 「于」在中文句式里连接日期(加入于 2024-01-01),英文不需要对应词。
|
||||||
|
// 这里保留原词而非空串:walk() 命中后用译文整体替换原文,空串会把
|
||||||
|
// 文字抹掉;同时该键实际不会被单独命中(源码中是「加入于」整串)。
|
||||||
|
'于': '于',
|
||||||
'发了': 'Posted',
|
'发了': 'Posted',
|
||||||
'个帖子': ' posts',
|
'个帖子': ' posts',
|
||||||
'帖': ' posts',
|
'帖': ' posts',
|
||||||
@@ -554,6 +724,170 @@ const TRANSLATIONS = {
|
|||||||
|
|
||||||
// ===== 论坛名称 =====
|
// ===== 论坛名称 =====
|
||||||
'论坛名称': 'Forum Name',
|
'论坛名称': 'Forum Name',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:操作状态与错误提示 =====
|
||||||
|
'保存失败:': 'Save failed: ',
|
||||||
|
'编辑成功!': 'Edited successfully!',
|
||||||
|
'编辑失败:': 'Edit failed: ',
|
||||||
|
'操作失败:': 'Operation failed: ',
|
||||||
|
'打开私信失败:': 'Failed to open messages: ',
|
||||||
|
'登录失败:': 'Login failed: ',
|
||||||
|
'发布失败:': 'Publish failed: ',
|
||||||
|
'发送失败:': 'Send failed: ',
|
||||||
|
'恢复码生成失败:': 'Failed to generate recovery codes: ',
|
||||||
|
'回复失败:': 'Reply failed: ',
|
||||||
|
'获取恢复码失败:': 'Failed to load recovery codes: ',
|
||||||
|
'举报失败:': 'Report failed: ',
|
||||||
|
'删除失败:': 'Delete failed: ',
|
||||||
|
'上传失败:': 'Upload failed: ',
|
||||||
|
'添加失败:': 'Add failed: ',
|
||||||
|
'重新生成失败:': 'Regeneration failed: ',
|
||||||
|
'注册失败:': 'Registration failed: ',
|
||||||
|
'页面加载失败:': 'Failed to load page: ',
|
||||||
|
'加载失败:': 'Failed to load: ',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:表单校验与按钮 =====
|
||||||
|
'保存修改': 'Save Changes',
|
||||||
|
'密码至少6位': 'Password must be at least 6 characters',
|
||||||
|
'新密码至少6位': 'New password must be at least 6 characters',
|
||||||
|
'验证码错误,请重新计算': 'Incorrect captcha, please try again',
|
||||||
|
'用户名不能为空': 'Username cannot be empty',
|
||||||
|
'请输入论坛名称': 'Please enter a forum name',
|
||||||
|
'请填写回复内容': 'Please enter your reply',
|
||||||
|
'页面名称只允许字母、数字、短横线和下划线': 'Page name may only contain letters, numbers, hyphens and underscores',
|
||||||
|
'移除': 'Remove',
|
||||||
|
'名称': 'Name',
|
||||||
|
'图片': 'Image',
|
||||||
|
'未知': 'Unknown',
|
||||||
|
'系统': 'System',
|
||||||
|
'无权限访问': 'Access denied',
|
||||||
|
'匿名用户': 'Anonymous',
|
||||||
|
'发布中...': 'Publishing...',
|
||||||
|
'上传图片中...': 'Uploading image...',
|
||||||
|
'松开上传': 'Release to upload',
|
||||||
|
'每篇帖子最多上传 6 张图片': 'Up to 6 images per post',
|
||||||
|
'上传响应无效': 'Invalid upload response',
|
||||||
|
'图片上传失败': 'Image upload failed',
|
||||||
|
'已选择:': 'Selected:',
|
||||||
|
'举报不成立': 'Report dismissed',
|
||||||
|
'已删除违规帖子': 'Removed the violating post',
|
||||||
|
'暂无用户': 'No users',
|
||||||
|
'暂无友情链接': 'No links',
|
||||||
|
'暂无消息': 'No messages',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:确认对话框 =====
|
||||||
|
'确定要': 'Are you sure you want to ',
|
||||||
|
'置顶吗?': '?',
|
||||||
|
'确定要退出吗?': 'Are you sure you want to log out?',
|
||||||
|
'确定删除该链接吗?': 'Delete this link?',
|
||||||
|
'确定要删除这条回复吗?': 'Delete this reply?',
|
||||||
|
'确定要删除这条帖子吗?': 'Delete this post?',
|
||||||
|
'确定要删除这个页面吗?': 'Delete this page?',
|
||||||
|
'确定要删除该帖子并标记举报为已处理吗?': 'Delete this post and mark the report as handled?',
|
||||||
|
'确定要删除自定义 CSS 吗?将恢复默认样式。': 'Delete the custom CSS? The default styles will be restored.',
|
||||||
|
'重新生成将替换所有旧的恢复码,确定继续吗?': 'Regenerating will replace all existing recovery codes. Continue?',
|
||||||
|
|
||||||
|
// ===== 补充覆盖:混合文案 =====
|
||||||
|
'当有人回复你的帖子或处理你的举报时,会在这里通知你': 'You will be notified here when someone replies to your post or your report is handled',
|
||||||
|
'举报已提交,管理员将尽快处理': 'Report submitted. An administrator will review it shortly',
|
||||||
|
'注册成功,但自动登录失败,请手动登录:': 'Registration succeeded, but automatic login failed. Please log in manually: ',
|
||||||
|
'注册并登录成功,但恢复码生成失败。请稍后在设置中重新生成。': 'Registered and signed in, but recovery codes could not be generated. Please regenerate them later in Settings.',
|
||||||
|
'支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染': 'Supports HTML, CSS (<style>) and JS (<script>). Content renders in an isolated sandbox',
|
||||||
|
|
||||||
|
// ===== 动态文本前缀 =====
|
||||||
|
// 「剩余 N 个可用恢复码」由模板字符串生成,整串无法命中词典,
|
||||||
|
// 因此登记可命中的固定片段。注意这里不能译成空串:万一该词以
|
||||||
|
// 独立文本节点出现,空串会把文字抹掉。
|
||||||
|
'剩余': 'Remaining:',
|
||||||
|
'个可用恢复码': 'recovery codes remaining',
|
||||||
|
'原因:': 'Reason: ',
|
||||||
|
'状态:': 'Status: ',
|
||||||
|
'处理人:': 'Handled by: ',
|
||||||
|
'帖子:': 'Post: ',
|
||||||
|
|
||||||
|
// ===== 确认对话框 =====
|
||||||
|
'请确认': 'Confirm',
|
||||||
|
'确定': 'OK',
|
||||||
|
'删除回复': 'Delete Reply',
|
||||||
|
'删除友链': 'Delete Link',
|
||||||
|
'删除页面': 'Delete Page',
|
||||||
|
'修改用户角色': 'Change User Role',
|
||||||
|
'重新生成恢复码': 'Regenerate Recovery Codes',
|
||||||
|
'退出登录': 'Logout',
|
||||||
|
|
||||||
|
// ===== 用户屏蔽 =====
|
||||||
|
'屏蔽': 'Block',
|
||||||
|
'解除屏蔽': 'Unblock',
|
||||||
|
'已屏蔽': 'Blocked',
|
||||||
|
'会话': 'Chats',
|
||||||
|
'屏蔽用户': 'Block User',
|
||||||
|
'已屏蔽该用户': 'User blocked',
|
||||||
|
'已解除屏蔽': 'User unblocked',
|
||||||
|
'还没有屏蔽任何人': 'You have not blocked anyone',
|
||||||
|
'加载中…': 'Loading…',
|
||||||
|
'加载失败': 'Failed to load',
|
||||||
|
|
||||||
|
// ===== 私信用户搜索 =====
|
||||||
|
'搜索用户名开始私信…': 'Search users to start a chat…',
|
||||||
|
'搜索用户': 'Search users',
|
||||||
|
'没有找到匹配的用户': 'No matching users found',
|
||||||
|
'点击发送私信': 'Click to send a message',
|
||||||
|
'对方回复前还可发送': 'You can send',
|
||||||
|
'条消息': 'more messages before they reply',
|
||||||
|
'对方回复前无法继续发送,请等待对方回复': 'You cannot send more until they reply',
|
||||||
|
'搜索中…': 'Searching…',
|
||||||
|
'搜索失败:': 'Search failed: ',
|
||||||
|
|
||||||
|
// ===== 帖子搜索 =====
|
||||||
|
'搜索帖子…': 'Search posts…',
|
||||||
|
'清除搜索': 'Clear search',
|
||||||
|
'请输入搜索关键词': 'Please enter a search term',
|
||||||
|
'搜索关键词过长(最多 100 字)': 'Search term is too long (max 100 characters)',
|
||||||
|
'没有找到相关帖子': 'No matching posts found',
|
||||||
|
'试试其他关键词,或检查是否有错别字': 'Try different keywords, or check for typos',
|
||||||
|
|
||||||
|
// ===== SMTP 与邮箱验证 =====
|
||||||
|
'邮件设置': 'Email Settings',
|
||||||
|
'启用邮件发送': 'Enable email sending',
|
||||||
|
'SMTP 服务器': 'SMTP Server',
|
||||||
|
'端口': 'Port',
|
||||||
|
'加密方式': 'Encryption',
|
||||||
|
'密码 / 授权码': 'Password / App Password',
|
||||||
|
'发件人名称': 'Sender Name',
|
||||||
|
'发件人邮箱': 'Sender Email',
|
||||||
|
'保存配置': 'Save Settings',
|
||||||
|
'发送测试邮件': 'Send Test Email',
|
||||||
|
'清除密码': 'Clear Password',
|
||||||
|
'注册邮箱验证': 'Email Verification on Signup',
|
||||||
|
'要求注册时验证邮箱': 'Require email verification on signup',
|
||||||
|
'获取验证码': 'Get Code',
|
||||||
|
'邮箱验证码': 'Email Code',
|
||||||
|
'配置完整,可以发信': 'Configuration complete, email is ready',
|
||||||
|
'尚未配置完成,邮件功能不可用': 'Configuration incomplete, email is unavailable',
|
||||||
|
'验证码已发送,请查收邮件': 'Verification code sent, please check your inbox',
|
||||||
|
'请输入邮箱验证码': 'Please enter the email verification code',
|
||||||
|
'请输入有效邮箱': 'Please enter a valid email address',
|
||||||
|
'该邮箱已被注册': 'This email is already registered',
|
||||||
|
'本站未开启邮箱验证': 'Email verification is not enabled on this site',
|
||||||
|
'请先获取验证码': 'Please request a verification code first',
|
||||||
|
'验证码已过期,请重新获取': 'The code has expired, please request a new one',
|
||||||
|
'尝试次数过多,请重新获取验证码': 'Too many attempts, please request a new code',
|
||||||
|
'验证码错误': 'Incorrect verification code',
|
||||||
|
'配置已保存': 'Settings saved',
|
||||||
|
'密码已清除': 'Password cleared',
|
||||||
|
'已开启注册邮箱验证': 'Email verification on signup enabled',
|
||||||
|
'已关闭注册邮箱验证': 'Email verification on signup disabled',
|
||||||
|
'加载配置失败:': 'Failed to load settings: ',
|
||||||
|
'已保存密码,留空则不修改': 'Password saved, leave blank to keep it',
|
||||||
|
'尚未设置密码': 'No password set yet',
|
||||||
|
'留空表示不修改已保存的密码': 'Leave blank to keep the saved password',
|
||||||
|
'通常为完整邮箱地址': 'Usually your full email address',
|
||||||
|
'例如:论坛名称': 'e.g. Forum name',
|
||||||
|
'注册验证码': 'Signup verification code',
|
||||||
|
'密码重置验证码': 'Password reset code',
|
||||||
|
'Forumlify SMTP 测试邮件': 'Forumlify SMTP test email',
|
||||||
|
'允许自签证书(仅自建邮件服务器需要)': 'Allow self-signed certificate (self-hosted servers only)',
|
||||||
|
'必须是你已在邮件服务商处验证过的域名下的地址,否则会被拒收。': 'Must be an address on a domain you have verified with your email provider, otherwise it will be rejected.',
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+58
-32
@@ -14,15 +14,16 @@ function switchToPost(postId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function showPostPage(postId) {
|
function showPostPage(postId) {
|
||||||
document.getElementById('app').style.display = 'none';
|
const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
|
||||||
document.querySelectorAll('.page-slide').forEach(el => {
|
|
||||||
el.classList.remove('active', 'slide-out');
|
|
||||||
});
|
|
||||||
const el = document.getElementById('pagePost');
|
const el = document.getElementById('pagePost');
|
||||||
el.classList.add('active');
|
|
||||||
el.style.animation = 'none';
|
// 先让其他覆盖页滑出(从帖子直接跳到用户主页之类的情况)
|
||||||
void el.offsetHeight;
|
document.querySelectorAll('.page-slide.active').forEach(other => {
|
||||||
el.style.animation = '';
|
if (other !== el) hideSlide(other, { back: goingBack });
|
||||||
|
});
|
||||||
|
|
||||||
|
// 首页留在背景中下沉,新页面从屏幕外滑入
|
||||||
|
showSlide(el, { back: goingBack });
|
||||||
currentPage = 'post';
|
currentPage = 'post';
|
||||||
renderPostDetail(postId);
|
renderPostDetail(postId);
|
||||||
}
|
}
|
||||||
@@ -30,7 +31,7 @@ function showPostPage(postId) {
|
|||||||
async function renderPostDetail(postId) {
|
async function renderPostDetail(postId) {
|
||||||
const container = document.getElementById('postDetailContent');
|
const container = document.getElementById('postDetailContent');
|
||||||
const replyArea = document.getElementById('replyArea');
|
const replyArea = document.getElementById('replyArea');
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
container.innerHTML = Skeleton.postDetail() + Skeleton.replyItem() + Skeleton.replyItem();
|
||||||
replyArea.style.display = 'none';
|
replyArea.style.display = 'none';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -57,11 +58,13 @@ async function renderPostDetail(postId) {
|
|||||||
const renderedContent = renderMarkdown(post.content || '');
|
const renderedContent = renderMarkdown(post.content || '');
|
||||||
|
|
||||||
// 签名渲染
|
// 签名渲染
|
||||||
|
// 详情页保留签名展示。补上类名以便统一样式定位——列表页的同类元素
|
||||||
|
// 正是靠 .post-signature 隐藏的,此前详情页只有行内样式,无法选中。
|
||||||
let signatureHtml = '';
|
let signatureHtml = '';
|
||||||
if (post.signature) {
|
if (post.signature) {
|
||||||
const sigContent = renderMarkdown(post.signature);
|
const sigContent = renderMarkdown(post.signature);
|
||||||
signatureHtml = `
|
signatureHtml = `
|
||||||
<div style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
<div class="post-signature" style="margin-top:16px;padding-top:12px;border-top:1px solid var(--border-light);font-size:12px;color:var(--text-secondary);">
|
||||||
${sigContent}
|
${sigContent}
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
@@ -86,6 +89,10 @@ async function renderPostDetail(postId) {
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
|
||||||
删除
|
删除
|
||||||
</button>` : ''}
|
</button>` : ''}
|
||||||
|
${currentUser ? `<button class="btn-sm btn-secondary" id="detailReportBtn" data-postid="${post.id}" style="padding:4px 10px;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/></svg>
|
||||||
|
举报
|
||||||
|
</button>` : ''}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
|
<div class="post-content" style="font-size:16px;line-height:1.8;">${renderedContent}</div>
|
||||||
@@ -148,13 +155,18 @@ async function renderPostDetail(postId) {
|
|||||||
// 置顶按钮
|
// 置顶按钮
|
||||||
const pinBtn = document.getElementById('pinPostBtn');
|
const pinBtn = document.getElementById('pinPostBtn');
|
||||||
if (pinBtn) {
|
if (pinBtn) {
|
||||||
pinBtn.addEventListener('click', function() {
|
pinBtn.addEventListener('click', async function() {
|
||||||
const postId = this.dataset.postid;
|
const postId = this.dataset.postid;
|
||||||
if (!confirm('确定要' + (this.textContent.includes('取消') ? '取消' : '') + '置顶吗?')) return;
|
const unpin = this.textContent.includes('取消');
|
||||||
|
const ok = await showConfirm('确定要' + (unpin ? '取消' : '') + '置顶吗?', {
|
||||||
|
title: unpin ? '取消置顶' : '置顶帖子',
|
||||||
|
confirmText: unpin ? '取消置顶' : '置顶',
|
||||||
|
});
|
||||||
|
if (!ok) return;
|
||||||
API.togglePinPost(postId).then(() => {
|
API.togglePinPost(postId).then(() => {
|
||||||
renderPostDetail(postId);
|
renderPostDetail(postId);
|
||||||
renderFeed();
|
renderFeed();
|
||||||
}).catch(err => alert('操作失败:' + err.message));
|
}).catch(err => showToast('操作失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,27 +183,41 @@ async function renderPostDetail(postId) {
|
|||||||
|
|
||||||
const deleteBtn = document.getElementById('detailDeleteBtn');
|
const deleteBtn = document.getElementById('detailDeleteBtn');
|
||||||
if (deleteBtn) {
|
if (deleteBtn) {
|
||||||
deleteBtn.addEventListener('click', function() {
|
deleteBtn.addEventListener('click', async function() {
|
||||||
if (confirm('确定要删除这条帖子吗?')) {
|
const ok = await showConfirm('确定要删除这条帖子吗?', {
|
||||||
API.deletePost(postId).then(() => {
|
title: '删除帖子', confirmText: '删除', danger: true,
|
||||||
alert('删除成功');
|
});
|
||||||
switchPage('feed');
|
if (!ok) return;
|
||||||
renderFeed();
|
API.deletePost(postId).then(() => {
|
||||||
renderStats();
|
showToast('删除成功', 'success');
|
||||||
}).catch(err => alert('删除失败:' + err.message));
|
// switchPage('feed') 内部已经会重新渲染列表、统计与友链,
|
||||||
}
|
// 此处不可再调一次,否则这些接口会各发出两次请求。
|
||||||
|
navigateBackToFeed();
|
||||||
|
}).catch(err => showToast('删除失败:' + err.message, 'error'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 举报按钮:原先只在列表卡片上,现移到详情页。
|
||||||
|
// 提交逻辑在 app.js 中读取 reportTargetPostId,这里只负责记录目标并打开弹窗。
|
||||||
|
const reportBtn = document.getElementById('detailReportBtn');
|
||||||
|
if (reportBtn) {
|
||||||
|
reportBtn.addEventListener('click', function() {
|
||||||
|
reportTargetPostId = this.dataset.postid;
|
||||||
|
document.getElementById('reportModal').classList.add('active');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
document.querySelectorAll('.reply-delete-btn').forEach(btn => {
|
document.querySelectorAll('.reply-delete-btn').forEach(btn => {
|
||||||
btn.addEventListener('click', function(e) {
|
btn.addEventListener('click', async function(e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
const replyId = this.dataset.replyid;
|
const replyId = this.dataset.replyid;
|
||||||
if (confirm('确定要删除这条回复吗?')) {
|
const ok = await showConfirm('确定要删除这条回复吗?', {
|
||||||
API.deleteReply(replyId).then(() => {
|
title: '删除回复', confirmText: '删除', danger: true,
|
||||||
renderPostDetail(postId);
|
});
|
||||||
}).catch(err => alert('删除失败:' + err.message));
|
if (!ok) return;
|
||||||
}
|
API.deleteReply(replyId).then(() => {
|
||||||
|
renderPostDetail(postId);
|
||||||
|
}).catch(err => showToast('删除失败:' + err.message, 'error'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -220,12 +246,12 @@ async function renderPostDetail(postId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleReplySubmit(postId) {
|
async function handleReplySubmit(postId) {
|
||||||
if (!currentUser) { alert('请先登录'); return; }
|
if (!currentUser) { showToast('请先登录', 'warning'); return; }
|
||||||
const content = document.getElementById('replyContent').value.trim();
|
const content = document.getElementById('replyContent').value.trim();
|
||||||
const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
|
const captchaInput = document.getElementById('replyCaptchaInput').value.trim();
|
||||||
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
|
const captchaAnswer = parseInt(document.getElementById('replyCaptchaInput').dataset.answer);
|
||||||
if (!content) { alert('请填写回复内容'); return; }
|
if (!content) { showToast('请填写回复内容', 'warning'); return; }
|
||||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reply'); return; }
|
if (parseInt(captchaInput) !== captchaAnswer) { showToast('验证码错误,请重新计算', 'error'); refreshCaptcha('reply'); return; }
|
||||||
try {
|
try {
|
||||||
await API.createReply(postId, content);
|
await API.createReply(postId, content);
|
||||||
|
|
||||||
@@ -235,6 +261,6 @@ async function handleReplySubmit(postId) {
|
|||||||
}
|
}
|
||||||
renderStats();
|
renderStats();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('回复失败:' + err.message);
|
showToast('回复失败:' + err.message, 'error');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+133
@@ -0,0 +1,133 @@
|
|||||||
|
// ============================================================
|
||||||
|
// 💀 骨架屏生成器
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// 用与真实内容同构的灰块替代「加载中...」文字,让等待期间就能看出
|
||||||
|
// 版面结构,内容出现时也不会发生明显的布局跳动。
|
||||||
|
//
|
||||||
|
// 所有函数返回 HTML 字符串,由调用方写入容器。
|
||||||
|
// 数量刻意与首页默认每页条数(20)不同——只画 3~5 条即可,
|
||||||
|
// 画满 20 条反而增加渲染负担,而用户在下一次绘制前看不完。
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
const Skeleton = {
|
||||||
|
// 单张帖子卡片:头像 + 用户名 + 标题 + 正文两行
|
||||||
|
postCard({ withThumbs = false } = {}) {
|
||||||
|
return `
|
||||||
|
<div class="skeleton-card">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line skeleton-title w-60"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-80"></div>
|
||||||
|
${withThumbs ? '<div class="skeleton-thumbs"><div class="skeleton-thumb"></div><div class="skeleton-thumb"></div></div>' : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 帖子列表
|
||||||
|
// 数量不宜过多:骨架卡片是按「理想内容」画的,实际帖子往往更短
|
||||||
|
// (标题一行、正文一两行),画太多会在真实内容出现时造成容器高度
|
||||||
|
// 骤降,页面内容整体上跳。用 3 张作为折中。
|
||||||
|
postList(count = 3) {
|
||||||
|
let html = '';
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
// 第二张带缩略图占位,更接近真实列表的参差感
|
||||||
|
html += this.postCard({ withThumbs: i === 1 });
|
||||||
|
}
|
||||||
|
return html;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 帖子详情:标题 + 多行正文 + 回复区
|
||||||
|
postDetail() {
|
||||||
|
return `
|
||||||
|
<div class="skeleton-card">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line skeleton-title w-45"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-100"></div>
|
||||||
|
<div class="skeleton-line w-60"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 回复条目
|
||||||
|
replyItem() {
|
||||||
|
return `
|
||||||
|
<div class="skeleton-card" style="padding:14px 18px;">
|
||||||
|
<div class="skeleton-header">
|
||||||
|
<div class="skeleton-avatar" style="width:28px;height:28px;"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton-line w-80"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 表格类列表(管理后台的用户 / 日志 / 友链)
|
||||||
|
tableRows(count = 6) {
|
||||||
|
let html = '';
|
||||||
|
for (let i = 0; i < count; i++) {
|
||||||
|
// 三列宽度固定,模拟表格的列对齐
|
||||||
|
html += `
|
||||||
|
<div class="skeleton-row">
|
||||||
|
<div class="skeleton-line" style="width:32%;margin-bottom:0;"></div>
|
||||||
|
<div class="skeleton-line" style="width:22%;margin-bottom:0;"></div>
|
||||||
|
<div class="skeleton-line" style="width:16%;margin-bottom:0;"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
return html;
|
||||||
|
},
|
||||||
|
|
||||||
|
// 用户主页
|
||||||
|
userProfile() {
|
||||||
|
return `
|
||||||
|
<div class="skeleton-card" style="text-align:center;padding:28px;">
|
||||||
|
<div class="skeleton-avatar" style="width:64px;height:64px;margin:0 auto 14px;"></div>
|
||||||
|
<div class="skeleton-line w-30" style="margin:0 auto 10px;"></div>
|
||||||
|
<div class="skeleton-line w-45" style="margin:0 auto;"></div>
|
||||||
|
</div>
|
||||||
|
${this.postList(2)}
|
||||||
|
`;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// 挂到 window 供各模块使用(各文件都是普通 script,共享全局作用域)
|
||||||
|
window.Skeleton = Skeleton;
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 首屏预置骨架屏
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// 真正的列表渲染要等 i18n 初始化完成后才触发(DOMContentLoaded 之后
|
||||||
|
// 还有 200ms 延迟)。若不提前占位,用户会先看到一段「加载中...」
|
||||||
|
// 文字,等骨架屏出现时数据往往已经回来了,等于白做。
|
||||||
|
//
|
||||||
|
// 这里在脚本执行时(早于 DOMContentLoaded)就把骨架屏写好,让它在
|
||||||
|
// 第一帧就可见。renderFeed 拿到数据后会直接覆盖这个容器。
|
||||||
|
// ============================================================
|
||||||
|
(function primeSkeleton() {
|
||||||
|
function insert() {
|
||||||
|
const list = document.getElementById('postList');
|
||||||
|
if (list && !list.dataset.loaded) {
|
||||||
|
list.innerHTML = Skeleton.postList(3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (document.readyState === 'loading') {
|
||||||
|
// DOM 尚未就绪时,解析到 postList 之后再插入;
|
||||||
|
// 用 DOMContentLoaded 会偏晚,因此监听 readystatechange 的
|
||||||
|
// interactive 阶段。
|
||||||
|
document.addEventListener('readystatechange', function onReady() {
|
||||||
|
if (document.readyState !== 'loading') {
|
||||||
|
document.removeEventListener('readystatechange', onReady);
|
||||||
|
insert();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
insert();
|
||||||
|
}
|
||||||
|
})();
|
||||||
+77
-13
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
async function renderUserProfile(username) {
|
async function renderUserProfile(username) {
|
||||||
const container = document.getElementById('userProfileContent');
|
const container = document.getElementById('userProfileContent');
|
||||||
container.innerHTML = '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
|
container.innerHTML = Skeleton.userProfile();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 使用公开接口 /users/profile/:username
|
// 使用公开接口 /users/profile/:username
|
||||||
@@ -22,6 +22,16 @@ async function renderUserProfile(username) {
|
|||||||
|
|
||||||
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
|
const avatar = user.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(user.username) + '&background=6366f1&color=fff&size=128';
|
||||||
|
|
||||||
|
// 已登录且不是本人时,查一次屏蔽关系,用于决定按钮文案
|
||||||
|
let blockStatus = { blocked_by_me: false, blocked_me: false };
|
||||||
|
if (currentUser && currentUser.id !== user.id) {
|
||||||
|
try {
|
||||||
|
blockStatus = await API.getBlockStatus(user.id);
|
||||||
|
} catch (err) {
|
||||||
|
// 查询失败时按未屏蔽处理,不阻断页面渲染
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let html = `
|
let html = `
|
||||||
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
|
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:32px;text-align:center;">
|
||||||
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
|
<img src="${escapeHTML(safeURL(avatar, { image: true }))}" style="width:96px;height:96px;border-radius:50%;object-fit:cover;border:3px solid var(--primary);" />
|
||||||
@@ -33,10 +43,26 @@ async function renderUserProfile(username) {
|
|||||||
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
|
${user.role === 'admin' ? '<span style="color:var(--primary);font-weight:600;">🛡️ 管理员</span>' : ''}
|
||||||
</div>
|
</div>
|
||||||
${currentUser && currentUser.id !== user.id ? `
|
${currentUser && currentUser.id !== user.id ? `
|
||||||
<button id="dmBtn" class="btn-primary" style="margin-top:16px;padding:8px 24px;">
|
<div style="display:flex;justify-content:center;gap:10px;margin-top:16px;flex-wrap:wrap;">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
<!-- 被我屏蔽时不给出发私信入口,避免必然失败的尝试 -->
|
||||||
发私信
|
${blockStatus.blocked_by_me ? '' : `
|
||||||
</button>
|
<button id="dmBtn" class="btn-primary" style="padding:8px 24px;">
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:middle;margin-right:6px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||||
|
发私信
|
||||||
|
</button>
|
||||||
|
`}
|
||||||
|
<button id="blockBtn" class="btn-secondary ${blockStatus.blocked_by_me ? 'is-blocked' : ''}"
|
||||||
|
data-userid="${escapeHTML(user.id)}" data-username="${escapeHTML(user.username)}"
|
||||||
|
data-blocked="${blockStatus.blocked_by_me ? '1' : '0'}"
|
||||||
|
style="padding:8px 20px;">
|
||||||
|
${blockStatus.blocked_by_me ? '解除屏蔽' : '屏蔽'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
${blockStatus.blocked_by_me ? `
|
||||||
|
<p style="margin-top:10px;font-size:12px;color:var(--text-light);">
|
||||||
|
已屏蔽该用户:你不再看到 TA 的帖子与回复,TA 也无法给你发私信
|
||||||
|
</p>
|
||||||
|
` : ''}
|
||||||
` : ''}
|
` : ''}
|
||||||
</div>
|
</div>
|
||||||
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
|
<h3 style="margin:24px 0 16px;font-size:18px;">📝 发布的帖子</h3>
|
||||||
@@ -72,21 +98,59 @@ async function renderUserProfile(username) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 屏蔽 / 解除屏蔽。两者都需要确认——屏蔽会影响双方的内容可见性,
|
||||||
|
// 属于不容易察觉后果的操作。
|
||||||
|
const blockBtn = document.getElementById('blockBtn');
|
||||||
|
if (blockBtn) {
|
||||||
|
blockBtn.addEventListener('click', async function() {
|
||||||
|
const targetId = this.dataset.userid;
|
||||||
|
const targetName = this.dataset.username;
|
||||||
|
const isBlocked = this.dataset.blocked === '1';
|
||||||
|
|
||||||
|
const ok = await showConfirm(
|
||||||
|
isBlocked
|
||||||
|
? `解除对「${targetName}」的屏蔽?解除后你将继续看到 TA 的帖子和回复,TA 也能再次给你发私信。`
|
||||||
|
: `确定屏蔽「${targetName}」?屏蔽后你不再看到 TA 的帖子和回复,TA 也无法给你发私信。`,
|
||||||
|
{
|
||||||
|
title: isBlocked ? '解除屏蔽' : '屏蔽用户',
|
||||||
|
confirmText: isBlocked ? '解除屏蔽' : '屏蔽',
|
||||||
|
danger: !isBlocked,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!ok) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isBlocked) {
|
||||||
|
await API.unblockUser(targetId);
|
||||||
|
showToast('已解除屏蔽', 'success');
|
||||||
|
} else {
|
||||||
|
await API.blockUser(targetId);
|
||||||
|
showToast('已屏蔽该用户', 'success');
|
||||||
|
}
|
||||||
|
// 重新渲染以更新按钮状态与提示
|
||||||
|
renderUserProfile(user.username);
|
||||||
|
} catch (err) {
|
||||||
|
showToast(err.message, 'error');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
|
container.innerHTML = '<div style="text-align:center;color:#ef4444;padding:40px 0;">加载失败:' + escapeHTML(err.message) + '</div>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function showUserPage(username) {
|
function showUserPage(username) {
|
||||||
document.getElementById('app').style.display = 'none';
|
const goingBack = typeof window.isNavigatingBack === 'function' && window.isNavigatingBack();
|
||||||
document.querySelectorAll('.page-slide').forEach(el => {
|
|
||||||
el.classList.remove('active', 'slide-out');
|
|
||||||
});
|
|
||||||
const el = document.getElementById('pageUser');
|
const el = document.getElementById('pageUser');
|
||||||
el.classList.add('active');
|
|
||||||
el.style.animation = 'none';
|
// 先让其他覆盖页滑出(例如从帖子详情跳到用户主页)
|
||||||
void el.offsetHeight;
|
document.querySelectorAll('.page-slide.active').forEach(other => {
|
||||||
el.style.animation = '';
|
if (other !== el) hideSlide(other, { back: goingBack });
|
||||||
|
});
|
||||||
|
|
||||||
|
// 首页留在背景中下沉,新页面从屏幕外滑入
|
||||||
|
showSlide(el, { back: goingBack });
|
||||||
currentPage = 'user';
|
currentPage = 'user';
|
||||||
renderUserProfile(username);
|
renderUserProfile(username);
|
||||||
}
|
}
|
||||||
+203
@@ -0,0 +1,203 @@
|
|||||||
|
// ============================================================
|
||||||
|
// 邮件发送
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// SMTP 配置存在 settings 表中(key 前缀 smtp_),由管理员在后台
|
||||||
|
// 填写,因此无需重启服务即可生效。这里按需构建 transporter 并做
|
||||||
|
// 短时缓存,避免每次发信都重新握手。
|
||||||
|
//
|
||||||
|
// 安全约定:
|
||||||
|
// - 密码只写不读,任何接口都不会回显明文
|
||||||
|
// - 配置校验失败时给出可读的错误,而不是抛出底层异常
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
const nodemailer = require('nodemailer');
|
||||||
|
|
||||||
|
// 缓存 transporter:配置变更时通过 invalidateTransport() 失效
|
||||||
|
let cachedTransport = null;
|
||||||
|
let cachedSignature = null;
|
||||||
|
|
||||||
|
const SMTP_KEYS = [
|
||||||
|
'smtp_enabled',
|
||||||
|
'smtp_host',
|
||||||
|
'smtp_port',
|
||||||
|
'smtp_secure',
|
||||||
|
'smtp_user',
|
||||||
|
'smtp_password',
|
||||||
|
'smtp_from_name',
|
||||||
|
'smtp_from_email',
|
||||||
|
'smtp_allow_self_signed',
|
||||||
|
];
|
||||||
|
|
||||||
|
function invalidateTransport() {
|
||||||
|
if (cachedTransport && typeof cachedTransport.close === 'function') {
|
||||||
|
try { cachedTransport.close(); } catch { /* 忽略关闭异常 */ }
|
||||||
|
}
|
||||||
|
cachedTransport = null;
|
||||||
|
cachedSignature = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 settings 表读取 SMTP 配置并整理成对象
|
||||||
|
async function loadSmtpConfig(pool) {
|
||||||
|
const r = await pool.query(
|
||||||
|
'SELECT key, value FROM settings WHERE key = ANY($1::text[])',
|
||||||
|
[SMTP_KEYS]
|
||||||
|
);
|
||||||
|
const raw = {};
|
||||||
|
r.rows.forEach(row => { raw[row.key] = row.value; });
|
||||||
|
|
||||||
|
return {
|
||||||
|
enabled: raw.smtp_enabled === 'true',
|
||||||
|
host: raw.smtp_host || '',
|
||||||
|
port: Number(raw.smtp_port || 587),
|
||||||
|
// secure=true 指 465 端口的隐式 TLS;587 用 STARTTLS
|
||||||
|
secure: raw.smtp_secure === 'true',
|
||||||
|
user: raw.smtp_user || '',
|
||||||
|
password: raw.smtp_password || '',
|
||||||
|
fromName: raw.smtp_from_name || '',
|
||||||
|
fromEmail: raw.smtp_from_email || '',
|
||||||
|
allowSelfSigned: raw.smtp_allow_self_signed === 'true',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 判断配置是否足以发信
|
||||||
|
function isConfigComplete(config) {
|
||||||
|
return Boolean(
|
||||||
|
config.enabled &&
|
||||||
|
config.host &&
|
||||||
|
config.port > 0 && config.port <= 65535 &&
|
||||||
|
config.fromEmail
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildTransport(config) {
|
||||||
|
const options = {
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
secure: config.secure,
|
||||||
|
// 默认严格校验服务器证书。Resend、QQ、Gmail 等正规服务商都使用
|
||||||
|
// 可信证书,关掉校验只会削弱安全性、让中间人有机可乘。
|
||||||
|
// 自建 SMTP 若用自签证书,可在后台把「允许自签证书」打开。
|
||||||
|
tls: { rejectUnauthorized: !config.allowSelfSigned },
|
||||||
|
connectionTimeout: 10000,
|
||||||
|
greetingTimeout: 10000,
|
||||||
|
socketTimeout: 20000,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (config.user) {
|
||||||
|
options.auth = {
|
||||||
|
user: config.user,
|
||||||
|
// 部分服务商要求使用授权码或 API Key 而非登录密码:
|
||||||
|
// QQ/163 用授权码,Resend 用 re_ 开头的 API Key
|
||||||
|
pass: config.password,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return nodemailer.createTransport(options);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTransport(config) {
|
||||||
|
// 以 host/port/secure/user/password 作为缓存签名
|
||||||
|
const signature = [config.host, config.port, config.secure, config.user, config.password].join('|');
|
||||||
|
if (cachedTransport && cachedSignature === signature) return cachedTransport;
|
||||||
|
|
||||||
|
invalidateTransport();
|
||||||
|
cachedTransport = buildTransport(config);
|
||||||
|
cachedSignature = signature;
|
||||||
|
return cachedTransport;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatFrom(config) {
|
||||||
|
return config.fromName
|
||||||
|
? `"${config.fromName.replace(/"/g, '')}" <${config.fromEmail}>`
|
||||||
|
: config.fromEmail;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送一封邮件。调用方需先把配置读出来传入。
|
||||||
|
async function sendMail(config, { to, subject, text, html }) {
|
||||||
|
if (!isConfigComplete(config)) {
|
||||||
|
const error = new Error('SMTP 尚未配置完成');
|
||||||
|
error.code = 'SMTP_NOT_CONFIGURED';
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const transport = getTransport(config);
|
||||||
|
return transport.sendMail({
|
||||||
|
from: formatFrom(config),
|
||||||
|
to,
|
||||||
|
subject,
|
||||||
|
text,
|
||||||
|
html,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验连通性:用于后台「发送测试邮件」按钮
|
||||||
|
async function verifyConnection(config) {
|
||||||
|
if (!isConfigComplete(config)) {
|
||||||
|
const error = new Error('SMTP 尚未配置完成');
|
||||||
|
error.code = 'SMTP_NOT_CONFIGURED';
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
const transport = getTransport(config);
|
||||||
|
await transport.verify();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 把底层异常转成便于管理员理解的中文提示。
|
||||||
|
// 这里的每一条都对应实际会遇到的配置错误,措辞尽量指明「该去改哪里」,
|
||||||
|
// 而不是笼统地说「发送失败」。
|
||||||
|
function describeSmtpError(error) {
|
||||||
|
const code = error && error.code;
|
||||||
|
const message = (error && error.message) || '';
|
||||||
|
|
||||||
|
// 连接超时既可能是防火墙,也可能是端口与加密方式不匹配:
|
||||||
|
// 例如 465 只接受隐式 SSL,若按 STARTTLS 去连,服务器不会回应握手。
|
||||||
|
// 两种原因都给出来,避免排查方向被带偏。
|
||||||
|
if (code === 'ETIMEDOUT' || /timeout/i.test(message)) {
|
||||||
|
return '连接超时:请检查端口是否被防火墙拦截,并确认加密方式与端口匹配(465 用 SSL/TLS,587 用 STARTTLS)';
|
||||||
|
}
|
||||||
|
|
||||||
|
const map = {
|
||||||
|
EAUTH: '认证失败:请检查用户名与密码。QQ、163 等邮箱需填写「授权码」;Resend 的用户名固定为 resend、密码填写 re_ 开头的 API Key',
|
||||||
|
ECONNECTION: '无法连接到邮件服务器:请检查服务器地址与端口是否正确',
|
||||||
|
ESOCKET: '套接字错误:端口与加密方式不匹配(465 需选 SSL/TLS,587 选 STARTTLS),也可能是证书校验未通过',
|
||||||
|
EENVELOPE: '发件人或收件人地址被拒绝:请确认发件人邮箱属于已在邮件服务商处验证过的域名',
|
||||||
|
EDNS: '域名解析失败:请检查 SMTP 服务器地址是否拼写正确',
|
||||||
|
DEPTH_ZERO_SELF_SIGNED_CERT: '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」',
|
||||||
|
SELF_SIGNED_CERT_IN_CHAIN: '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」',
|
||||||
|
};
|
||||||
|
if (code && map[code]) return map[code];
|
||||||
|
|
||||||
|
// 部分证书错误不带 code,只体现在 message 里
|
||||||
|
if (/self.signed certificate/i.test(message)) {
|
||||||
|
return '证书校验失败:服务器使用了自签证书。若这是你自己的邮件服务器,可打开「允许自签证书」';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resend 会拒绝发往 example.com、test.com 等保留/测试域名,
|
||||||
|
// 以及未验证域名下的地址。原始报文是英文且较长,这里转成中文。
|
||||||
|
if (/Invalid `?to`? field/i.test(message) || /testing email address/i.test(message)) {
|
||||||
|
return '收件人邮箱被邮件服务商拒绝:请使用真实可收信的邮箱地址。'
|
||||||
|
+ 'Resend 不允许发送到 example.com、test.com 等测试域名,'
|
||||||
|
+ '也不允许从尚未验证的域名发信';
|
||||||
|
}
|
||||||
|
if (/domain is not verified|not verified/i.test(message)) {
|
||||||
|
return '发信域名尚未验证:请先在邮件服务商处完成发件域名的验证(配置 SPF / DKIM 记录)';
|
||||||
|
}
|
||||||
|
if (/API key is invalid|invalid.*api.*key/i.test(message)) {
|
||||||
|
return 'API Key 无效:请检查后台填写的密钥是否正确、是否已被撤销';
|
||||||
|
}
|
||||||
|
if (/rate limit|too many requests/i.test(message)) {
|
||||||
|
return '发送频率超出邮件服务商限制:请稍后再试,或升级服务商配额';
|
||||||
|
}
|
||||||
|
|
||||||
|
return message || '发送失败';
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
SMTP_KEYS,
|
||||||
|
loadSmtpConfig,
|
||||||
|
isConfigComplete,
|
||||||
|
sendMail,
|
||||||
|
verifyConnection,
|
||||||
|
invalidateTransport,
|
||||||
|
describeSmtpError,
|
||||||
|
};
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 邮箱验证支持
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 注册流程改为「先验证邮箱再建号」,因此需要一张表暂存验证码。
|
||||||
|
-- 验证码只存哈希,不存明文,避免库被读取后可直接冒用。
|
||||||
|
--
|
||||||
|
-- 同时新增 SMTP 配置项到 settings 表(key-value 结构,无需建表),
|
||||||
|
-- 由管理员在后台填写。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- 邮箱验证码:用于注册时的邮箱归属校验
|
||||||
|
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
-- 验证码的 sha256 摘要;与用户输入做定时安全比较
|
||||||
|
code_hash VARCHAR(64) NOT NULL,
|
||||||
|
-- 用途区分:register(注册)/ reset(找回密码)
|
||||||
|
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||||
|
-- 尝试次数,超过阈值即作废,防止暴力枚举 6 位数字
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 同一邮箱同一用途下只保留一条有效记录,靠下面的唯一索引约束
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_email_verifications_lookup
|
||||||
|
ON email_verifications (LOWER(email), purpose, created_at DESC);
|
||||||
|
|
||||||
|
-- 清理过期记录时使用
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||||
|
ON email_verifications (expires_at);
|
||||||
|
|
||||||
|
-- 每个邮箱+用途同时只允许一条未消费的记录,避免重复发送堆积
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||||
|
ON email_verifications (LOWER(email), purpose)
|
||||||
|
WHERE consumed_at IS NULL;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- SMTP 默认配置项
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 默认关闭。管理员在后台填写后才生效,因此现有部署升级后行为不变。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
INSERT INTO settings (key, value) VALUES
|
||||||
|
('smtp_enabled', 'false'),
|
||||||
|
('smtp_host', ''),
|
||||||
|
('smtp_port', '587'),
|
||||||
|
('smtp_secure', 'false'),
|
||||||
|
('smtp_user', ''),
|
||||||
|
('smtp_password', ''),
|
||||||
|
('smtp_from_name', ''),
|
||||||
|
('smtp_from_email', ''),
|
||||||
|
('smtp_allow_self_signed', 'false'),
|
||||||
|
('email_verify_required', 'false')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 用户邮箱验证标记
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 记录该账号注册时是否通过了邮箱验证,便于后续审计与运营。
|
||||||
|
-- 存量用户默认为 true:他们是在开启邮箱验证之前注册的,
|
||||||
|
-- 不应因为新功能而被标记为「未验证」。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- SMTP 增加「允许自签证书」开关
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 背景:邮件模块最初对所有 SMTP 服务器都关闭了 TLS 证书校验
|
||||||
|
-- (tls.rejectUnauthorized = false),以便兼容使用自签证书的自建
|
||||||
|
-- 邮件服务器。但这会削弱安全性——对 Resend、QQ、Gmail 等使用可信
|
||||||
|
-- 证书的正规服务商而言,关掉校验只会给中间人留下可乘之机。
|
||||||
|
--
|
||||||
|
-- 现改为默认严格校验,仅在以下情况才放行自签证书:
|
||||||
|
-- 部署者明确在后台打开该开关。
|
||||||
|
--
|
||||||
|
-- 003 已在部分部署中执行过,因此这里单独追加一版,
|
||||||
|
-- 让存量库也能拿到这个配置项。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
INSERT INTO settings (key, value) VALUES ('smtp_allow_self_signed', 'false')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 帖子搜索
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 搜索用 ILIKE 做子串匹配(见 server.js 的 /api/posts/search)。
|
||||||
|
-- 之所以不用 PostgreSQL 的全文检索(tsvector):它依赖分词,而
|
||||||
|
-- 中文分词需要额外安装 zhparser 等扩展,多数部署环境没有;ILIKE
|
||||||
|
-- 无需任何扩展即可正确匹配中文子串。
|
||||||
|
--
|
||||||
|
-- 索引用 pg_trgm 的 GIN 索引,实测效果分两种情况:
|
||||||
|
-- - 英文关键词(如 postgresql):走 Bitmap Index Scan,0.2ms,
|
||||||
|
-- 相比全表扫描快约 47 倍
|
||||||
|
-- - 中文关键词:pg_trgm 对中文难以切出有效 trigram,优化器仍选
|
||||||
|
-- 全表扫描。3000 条数据下约 7~9ms,可接受
|
||||||
|
-- 即索引对英文有效、对中文无效。许多技术论坛中英混排,保留仍有
|
||||||
|
-- 价值。
|
||||||
|
--
|
||||||
|
-- 注意:创建扩展需要相应权限。部分托管数据库不开放该权限,因此
|
||||||
|
-- 失败时仅提示,不影响后续迁移与功能——搜索本身不依赖扩展。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可正常使用,但英文关键词将无法走索引加速。', SQLERRM;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- 仅在扩展可用时才建索引
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
|
||||||
|
ON posts USING gin (title gin_trgm_ops);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
|
||||||
|
ON posts USING gin (content gin_trgm_ops);
|
||||||
|
ELSE
|
||||||
|
RAISE NOTICE '跳过 trigram 索引创建:pg_trgm 不可用。';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
-- ============================================================
|
||||||
|
-- 用户屏蔽
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 单向关系:blocker 屏蔽 blocked 之后
|
||||||
|
-- - blocked 不能再给 blocker 发私信(已有的会话也发不了)
|
||||||
|
-- - blocker 在帖子列表、详情与回复中不再看到 blocked 的内容
|
||||||
|
-- - blocked 仍可正常浏览 blocker 的公开内容(不通知、不暴露)
|
||||||
|
--
|
||||||
|
-- 之所以是单向而非互斥:屏蔽应当是「我选择不看某人的内容、也不让
|
||||||
|
-- 对方打扰我」,而不是让双方互相消失。被屏蔽方不会收到任何提示。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
-- 发起屏蔽的人
|
||||||
|
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
-- 被屏蔽的人
|
||||||
|
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
-- 同一对关系只能有一条
|
||||||
|
UNIQUE (blocker_id, blocked_id),
|
||||||
|
-- 不允许屏蔽自己
|
||||||
|
CHECK (blocker_id <> blocked_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 主查询方向:某人屏蔽了谁(用于过滤内容)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
|
||||||
|
|
||||||
|
-- 反向查询:某人被谁屏蔽(用于判断能否发私信)
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
|
||||||
Generated
+17
-61
@@ -14,11 +14,15 @@
|
|||||||
"express-rate-limit": "8.6.2",
|
"express-rate-limit": "8.6.2",
|
||||||
"helmet": "8.1.0",
|
"helmet": "8.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"multer": "2.2.0",
|
"multer": "2.4.0",
|
||||||
|
"nodemailer": "^7.0.9",
|
||||||
"pg": "^8.11.3"
|
"pg": "^8.11.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"supertest": "7.2.2"
|
"supertest": "7.2.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@noble/hashes": {
|
"node_modules/@noble/hashes": {
|
||||||
@@ -122,12 +126,6 @@
|
|||||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||||
"license": "BSD-3-Clause"
|
"license": "BSD-3-Clause"
|
||||||
},
|
},
|
||||||
"node_modules/buffer-from": {
|
|
||||||
"version": "1.1.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
|
||||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/busboy": {
|
"node_modules/busboy": {
|
||||||
"version": "1.6.0",
|
"version": "1.6.0",
|
||||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||||
@@ -200,21 +198,6 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/concat-stream": {
|
|
||||||
"version": "2.0.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
|
|
||||||
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
|
|
||||||
"engines": [
|
|
||||||
"node >= 6.0"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"buffer-from": "^1.0.0",
|
|
||||||
"inherits": "^2.0.3",
|
|
||||||
"readable-stream": "^3.0.2",
|
|
||||||
"typedarray": "^0.0.6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/content-disposition": {
|
"node_modules/content-disposition": {
|
||||||
"version": "0.5.4",
|
"version": "0.5.4",
|
||||||
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
|
||||||
@@ -919,14 +902,13 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/multer": {
|
"node_modules/multer": {
|
||||||
"version": "2.2.0",
|
"version": "2.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/multer/-/multer-2.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/multer/-/multer-2.4.0.tgz",
|
||||||
"integrity": "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ==",
|
"integrity": "sha512-7dqa0ZcFfzbefdTuIkzOSMvZWC0J7FLqBOjJUZvDCXShIURWKxAyTT1wHhnE5q19c7jOJf43IYYKjBmZVZmvhg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"append-field": "^1.0.0",
|
"append-field": "^1.0.0",
|
||||||
"busboy": "^1.6.0",
|
"busboy": "^1.6.0",
|
||||||
"concat-stream": "^2.0.0",
|
|
||||||
"type-is": "^1.6.18"
|
"type-is": "^1.6.18"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -946,6 +928,15 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/nodemailer": {
|
||||||
|
"version": "7.0.13",
|
||||||
|
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.13.tgz",
|
||||||
|
"integrity": "sha512-PNDFSJdP+KFgdsG3ZzMXCgquO7I6McjY2vlqILjtJd0hy8wEvtugS9xKRF2NWlPNGxvLCXlTNIae4serI7dinw==",
|
||||||
|
"license": "MIT-0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/object-assign": {
|
"node_modules/object-assign": {
|
||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||||
@@ -1185,20 +1176,6 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/readable-stream": {
|
|
||||||
"version": "3.6.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
|
||||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"inherits": "^2.0.3",
|
|
||||||
"string_decoder": "^1.1.1",
|
|
||||||
"util-deprecate": "^1.0.1"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": ">= 6"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/safe-buffer": {
|
"node_modules/safe-buffer": {
|
||||||
"version": "5.2.1",
|
"version": "5.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||||
@@ -1386,15 +1363,6 @@
|
|||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/string_decoder": {
|
|
||||||
"version": "1.3.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
|
|
||||||
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"safe-buffer": "~5.2.0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/superagent": {
|
"node_modules/superagent": {
|
||||||
"version": "10.3.0",
|
"version": "10.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/superagent/-/superagent-10.3.0.tgz",
|
||||||
@@ -1501,12 +1469,6 @@
|
|||||||
"node": ">= 0.6"
|
"node": ">= 0.6"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/typedarray": {
|
|
||||||
"version": "0.0.6",
|
|
||||||
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
|
|
||||||
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/unpipe": {
|
"node_modules/unpipe": {
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
|
||||||
@@ -1516,12 +1478,6 @@
|
|||||||
"node": ">= 0.8"
|
"node": ">= 0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/util-deprecate": {
|
|
||||||
"version": "1.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
|
||||||
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
|
|
||||||
"license": "MIT"
|
|
||||||
},
|
|
||||||
"node_modules/utils-merge": {
|
"node_modules/utils-merge": {
|
||||||
"version": "1.0.1",
|
"version": "1.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
|
||||||
|
|||||||
+2
-1
@@ -21,7 +21,8 @@
|
|||||||
"express-rate-limit": "8.6.2",
|
"express-rate-limit": "8.6.2",
|
||||||
"helmet": "8.1.0",
|
"helmet": "8.1.0",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"multer": "2.2.0",
|
"multer": "2.4.0",
|
||||||
|
"nodemailer": "^7.0.9",
|
||||||
"pg": "^8.11.3"
|
"pg": "^8.11.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
+93
@@ -287,3 +287,96 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_reports_unique_pending
|
|||||||
-- ============================================================
|
-- ============================================================
|
||||||
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||||
ON CONFLICT (key) DO NOTHING;
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 邮箱验证(对应 migrations/003_email_verification.sql)
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
-- 邮箱验证码:用于注册时的邮箱归属校验,以及通过邮箱找回密码
|
||||||
|
CREATE TABLE IF NOT EXISTS email_verifications (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
-- 验证码的 sha256 摘要,不存明文
|
||||||
|
code_hash VARCHAR(64) NOT NULL,
|
||||||
|
purpose VARCHAR(20) NOT NULL DEFAULT 'register',
|
||||||
|
-- 尝试次数,超过阈值即作废,防止暴力枚举 6 位数字
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
consumed_at TIMESTAMPTZ,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_email_verifications_lookup
|
||||||
|
ON email_verifications (LOWER(email), purpose, created_at DESC);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_email_verifications_expires
|
||||||
|
ON email_verifications (expires_at);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_email_verifications_active
|
||||||
|
ON email_verifications (LOWER(email), purpose)
|
||||||
|
WHERE consumed_at IS NULL;
|
||||||
|
|
||||||
|
-- 用户邮箱验证标记。存量用户默认为 true:他们是在开启邮箱验证之前
|
||||||
|
-- 注册的,不应因为新功能而被标记为「未验证」。
|
||||||
|
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT true;
|
||||||
|
|
||||||
|
-- SMTP 配置项(默认关闭,管理员在后台填写后生效)
|
||||||
|
INSERT INTO settings (key, value) VALUES
|
||||||
|
('smtp_enabled', 'false'),
|
||||||
|
('smtp_host', ''),
|
||||||
|
('smtp_port', '587'),
|
||||||
|
('smtp_secure', 'false'),
|
||||||
|
('smtp_user', ''),
|
||||||
|
('smtp_password', ''),
|
||||||
|
('smtp_from_name', ''),
|
||||||
|
('smtp_from_email', ''),
|
||||||
|
('smtp_allow_self_signed', 'false'),
|
||||||
|
('email_verify_required', 'false')
|
||||||
|
ON CONFLICT (key) DO NOTHING;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 帖子搜索(对应 migrations/005_post_search.sql)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 搜索用 ILIKE 子串匹配。trigram 索引对英文关键词有效(实测 0.2ms,
|
||||||
|
-- 比全表扫描快约 47 倍),对中文因难以切出有效 trigram 而仍走全表
|
||||||
|
-- 扫描(3000 条约 7~9ms,可接受)。
|
||||||
|
--
|
||||||
|
-- 创建扩展需要权限,部分托管数据库不开放,故失败时仅提示。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
EXCEPTION WHEN OTHERS THEN
|
||||||
|
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可用,但英文关键词不走索引。', SQLERRM;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
|
||||||
|
ON posts USING gin (title gin_trgm_ops);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
|
||||||
|
ON posts USING gin (content gin_trgm_ops);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- ============================================================
|
||||||
|
-- 用户屏蔽(对应 migrations/006_user_blocks.sql)
|
||||||
|
-- ------------------------------------------------------------
|
||||||
|
-- 单向关系:blocker 屏蔽 blocked 之后,blocked 不能给 blocker 发私信,
|
||||||
|
-- 且 blocker 在帖子与回复中不再看到 blocked 的内容。
|
||||||
|
-- 被屏蔽方不会收到任何提示。
|
||||||
|
-- ============================================================
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS user_blocks (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
blocker_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
blocked_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE (blocker_id, blocked_id),
|
||||||
|
CHECK (blocker_id <> blocked_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocker ON user_blocks(blocker_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_blocks_blocked ON user_blocks(blocked_id);
|
||||||
+15
-1
@@ -70,6 +70,20 @@ test('bcryptjs hashes passwords without native install scripts', async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('security-sensitive dependencies are on patched release lines', () => {
|
test('security-sensitive dependencies are on patched release lines', () => {
|
||||||
assert.match(multerPackage.version, /^2\.2\./);
|
// multer 2.2.0 及更早版本存在多个 DoS 与上传限制绕过漏洞
|
||||||
|
// (GHSA-wc9g-mqfw-jrwm 等),2.3.0 起修复。
|
||||||
|
// 这里断言「不低于已修复的版本」,而不是锁死某个小版本,
|
||||||
|
// 否则后续的安全升级反而会让测试失败。
|
||||||
|
const [major, minor] = multerPackage.version.split('.').map(Number);
|
||||||
|
const multerPatched = major > 2 || (major === 2 && minor >= 3);
|
||||||
|
assert.ok(
|
||||||
|
multerPatched,
|
||||||
|
`multer ${multerPackage.version} 低于已修复漏洞的 2.3.0`
|
||||||
|
);
|
||||||
|
|
||||||
assert.equal(projectPackage.dependencies['express-rate-limit'], '8.6.2');
|
assert.equal(projectPackage.dependencies['express-rate-limit'], '8.6.2');
|
||||||
|
assert.ok(
|
||||||
|
projectPackage.dependencies.nodemailer,
|
||||||
|
'nodemailer 是邮件功能的必需依赖'
|
||||||
|
);
|
||||||
});
|
});
|
||||||
Vendored
+88
@@ -0,0 +1,88 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
// 管理员初始化令牌(ADMIN_BOOTSTRAP_TOKEN)属于部署期的一次性机制,
|
||||||
|
// 不应暴露给普通注册用户。历史上它的输入框固定显示在注册模态框里,
|
||||||
|
// 每个来注册的人都会看到一个「管理员初始化令牌」字段,既困惑又等于
|
||||||
|
// 对外宣告存在提权入口。
|
||||||
|
//
|
||||||
|
// 现在的约定:输入框默认隐藏,只有 /api/settings 返回
|
||||||
|
// bootstrap_required === true 时才显示,该标志仅在「部署者配置了引导
|
||||||
|
// 令牌」且「系统尚无管理员」时为真。
|
||||||
|
//
|
||||||
|
// 以下断言不依赖数据库,直接在文本层面锁住这些约定。
|
||||||
|
|
||||||
|
const root = path.join(__dirname, '..');
|
||||||
|
const indexHTML = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
|
||||||
|
const authJS = fs.readFileSync(path.join(root, 'js', 'auth.js'), 'utf8');
|
||||||
|
const serverJS = fs.readFileSync(path.join(root, 'server.js'), 'utf8');
|
||||||
|
|
||||||
|
test('bootstrap token field is hidden by default in the markup', () => {
|
||||||
|
const field = indexHTML.match(/<input[^>]*id="regBootstrapToken"[^>]*>/i);
|
||||||
|
assert.ok(field, '注册模态框中找不到 regBootstrapToken 输入框');
|
||||||
|
assert.match(
|
||||||
|
field[0],
|
||||||
|
/style\s*=\s*"[^"]*display\s*:\s*none/i,
|
||||||
|
'regBootstrapToken 必须默认隐藏,仅在首次部署且已配置引导令牌时由脚本显示'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('/api/settings only exposes a boolean, never the token itself', () => {
|
||||||
|
const route = serverJS.match(/app\.get\('\/api\/settings'[\s\S]*?\n\}\);/);
|
||||||
|
assert.ok(route, '找不到 GET /api/settings 路由');
|
||||||
|
const body = route[0];
|
||||||
|
|
||||||
|
assert.match(
|
||||||
|
body,
|
||||||
|
/bootstrap_required/,
|
||||||
|
'接口需要返回 bootstrap_required 供前端判断是否显示初始化入口'
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
body,
|
||||||
|
/process\.env\.ADMIN_BOOTSTRAP_TOKEN/,
|
||||||
|
'bootstrap_required 必须依据是否配置了引导令牌来判断'
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
body,
|
||||||
|
/role\s*=\s*'admin'/,
|
||||||
|
'bootstrap_required 还必须检查是否已存在管理员'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 不得把令牌明文或其长度写进响应。
|
||||||
|
assert.doesNotMatch(
|
||||||
|
body,
|
||||||
|
/settings\.\w*token\w*\s*=\s*process\.env\.ADMIN_BOOTSTRAP_TOKEN/i,
|
||||||
|
'不得把引导令牌本身放进响应'
|
||||||
|
);
|
||||||
|
assert.doesNotMatch(
|
||||||
|
body,
|
||||||
|
/ADMIN_BOOTSTRAP_TOKEN\s*\)\s*\.\s*length|ADMIN_BOOTSTRAP_TOKEN\s*\.\s*length/,
|
||||||
|
'不得返回引导令牌的长度,避免泄露部署配置细节'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registration ignores the hidden field instead of submitting an empty token', () => {
|
||||||
|
// 字段隐藏时必须按「未提供」处理,否则会传空串进入后端的令牌校验
|
||||||
|
// 分支,让普通注册收到 403。
|
||||||
|
assert.match(
|
||||||
|
authJS,
|
||||||
|
/style\.display\s*!==\s*'none'/,
|
||||||
|
'读取 regBootstrapToken 前必须判断其是否可见'
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
authJS,
|
||||||
|
/bootstrap_required/,
|
||||||
|
'auth.js 需要依据 bootstrap_required 决定是否显示该字段'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('registration form still works without the bootstrap field', () => {
|
||||||
|
// 普通注册路径不得依赖该字段存在。
|
||||||
|
assert.match(
|
||||||
|
authJS,
|
||||||
|
/if\s*\(\s*bootstrapField\s*\)/,
|
||||||
|
'清理表单时必须对可能不存在的 bootstrap 字段做空值保护'
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
// i18n 采用「中文原文作 key」的外挂方案:js/i18n.js 里的 zh 词典登记
|
||||||
|
// 哪些中文需要翻译(键与值相同),en 词典提供对应译文;运行时遍历
|
||||||
|
// DOM,只有能在 zh 词典里精确命中的文本才会被替换。
|
||||||
|
//
|
||||||
|
// 因此「漏翻译」= 界面文案没被登记进词典。历史上曾有 60 余条界面文案
|
||||||
|
// (各类失败提示、表单校验、确认对话框)从未登记,切到英文后仍是中文。
|
||||||
|
// 这里直接从源码里抽出中文文案,断言它们都在词典里出现过。
|
||||||
|
|
||||||
|
const root = path.join(__dirname, '..');
|
||||||
|
const i18nSource = fs.readFileSync(path.join(root, 'js', 'i18n.js'), 'utf8');
|
||||||
|
|
||||||
|
// 取 zh 词典块(第一个 'zh': { ... } )。
|
||||||
|
function extractDict(source, lang) {
|
||||||
|
const startMatch = source.match(new RegExp(`'${lang}'\\s*:\\s*\\{`));
|
||||||
|
assert.ok(startMatch, `找不到 ${lang} 词典`);
|
||||||
|
const start = startMatch.index + startMatch[0].length;
|
||||||
|
// 从起点开始做花括号配平,避免被字符串里的括号干扰。
|
||||||
|
let depth = 1;
|
||||||
|
let i = start;
|
||||||
|
let inString = false;
|
||||||
|
let quote = '';
|
||||||
|
for (; i < source.length && depth > 0; i++) {
|
||||||
|
const ch = source[i];
|
||||||
|
const prev = source[i - 1];
|
||||||
|
if (inString) {
|
||||||
|
if (ch === quote && prev !== '\\') inString = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '"' || ch === "'" || ch === '`') { inString = true; quote = ch; continue; }
|
||||||
|
if (ch === '{') depth++;
|
||||||
|
else if (ch === '}') depth--;
|
||||||
|
}
|
||||||
|
return source.slice(start, i - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const zhBlock = extractDict(i18nSource, 'zh');
|
||||||
|
const enBlock = extractDict(i18nSource, 'en');
|
||||||
|
|
||||||
|
const keyPattern = /^\s*'((?:[^'\\]|\\.)*)'\s*:/gm;
|
||||||
|
const collectKeys = block => {
|
||||||
|
const keys = new Set();
|
||||||
|
let m;
|
||||||
|
keyPattern.lastIndex = 0;
|
||||||
|
while ((m = keyPattern.exec(block)) !== null) keys.add(m[1]);
|
||||||
|
return keys;
|
||||||
|
};
|
||||||
|
const zhKeys = collectKeys(zhBlock);
|
||||||
|
const enKeys = collectKeys(enBlock);
|
||||||
|
|
||||||
|
// 从源码里抽出所有中文文案。
|
||||||
|
function collectChineseLiterals() {
|
||||||
|
const literals = new Set();
|
||||||
|
const files = ['index.html', ...fs.readdirSync(path.join(root, 'js'))
|
||||||
|
.filter(f => f.endsWith('.js') && f !== 'i18n.js')
|
||||||
|
.map(f => path.join('js', f))];
|
||||||
|
|
||||||
|
const cjk = /[\u4e00-\u9fff]/;
|
||||||
|
for (const file of files) {
|
||||||
|
const full = path.join(root, file);
|
||||||
|
if (!fs.existsSync(full)) continue;
|
||||||
|
const text = fs.readFileSync(full, 'utf8');
|
||||||
|
// 引号包裹的中文串
|
||||||
|
for (const m of text.matchAll(/(['"`])([\u4e00-\u9fff][^'"`\n]{0,80}?)\1/g)) {
|
||||||
|
const value = m[2].trim();
|
||||||
|
if (cjk.test(value) && value.length >= 2) literals.add(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return literals;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('zh and en dictionaries define exactly the same keys', () => {
|
||||||
|
const missingInEn = [...zhKeys].filter(k => !enKeys.has(k));
|
||||||
|
const missingInZh = [...enKeys].filter(k => !zhKeys.has(k));
|
||||||
|
assert.deepEqual(missingInEn, [], `en 词典缺少:${missingInEn.join(', ')}`);
|
||||||
|
assert.deepEqual(missingInZh, [], `zh 词典缺少:${missingInZh.join(', ')}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no translation maps to an empty string', () => {
|
||||||
|
// walk() 命中词典后会用译文替换原文,空串会把界面文字抹掉。
|
||||||
|
const empties = [];
|
||||||
|
const pattern = /^\s*'((?:[^'\\]|\\.)*)'\s*:\s*''/gm;
|
||||||
|
let m;
|
||||||
|
pattern.lastIndex = 0;
|
||||||
|
while ((m = pattern.exec(enBlock)) !== null) empties.push(m[1]);
|
||||||
|
assert.deepEqual(empties, [], `以下条目的英文译文为空串:${empties.join(', ')}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('common failure prefixes are registered for translation', () => {
|
||||||
|
// 源码里的错误提示普遍是 「XX失败:」+ 具体原因 的形式,
|
||||||
|
// 与不带冒号的短词属于不同字符串,必须分别登记。
|
||||||
|
const prefixes = [
|
||||||
|
'保存失败:', '删除失败:', '操作失败:', '登录失败:', '发布失败:',
|
||||||
|
'上传失败:', '举报失败:', '注册失败:', '回复失败:', '添加失败:',
|
||||||
|
'发送失败:', '编辑失败:', '加载失败:',
|
||||||
|
];
|
||||||
|
const missing = prefixes.filter(k => !zhKeys.has(k));
|
||||||
|
assert.deepEqual(missing, [], `以下错误提示前缀未登记,切英文后仍显示中文:${missing.join(', ')}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('confirmation dialogs and form validation are registered', () => {
|
||||||
|
const required = [
|
||||||
|
'确定要退出吗?',
|
||||||
|
'确定要删除这条帖子吗?',
|
||||||
|
'确定要删除这条回复吗?',
|
||||||
|
'密码至少6位',
|
||||||
|
'验证码错误,请重新计算',
|
||||||
|
'请输入论坛名称',
|
||||||
|
'请填写回复内容',
|
||||||
|
'松开上传',
|
||||||
|
'暂无消息',
|
||||||
|
'未知',
|
||||||
|
'匿名用户',
|
||||||
|
];
|
||||||
|
const missing = required.filter(k => !zhKeys.has(k));
|
||||||
|
assert.deepEqual(missing, [], `以下文案未登记翻译:${missing.join(', ')}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('interface copy coverage is above the required floor', () => {
|
||||||
|
const literals = collectChineseLiterals();
|
||||||
|
const uncovered = [...literals].filter(lit => !zhKeys.has(lit));
|
||||||
|
|
||||||
|
// 允许少量无法静态登记的动态拼接串,但整体覆盖率必须保持在
|
||||||
|
// 高水位,防止再次出现大批文案漏登记的情况。
|
||||||
|
const coverage = 1 - uncovered.length / Math.max(literals.size, 1);
|
||||||
|
assert.ok(
|
||||||
|
coverage >= 0.9,
|
||||||
|
`界面中文文案覆盖率 ${(coverage * 100).toFixed(1)}% 低于 90%;未登记:${uncovered.join(' | ')}`
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
process.env.TRUST_PROXY = 'true';
|
||||||
|
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const request = require('supertest');
|
||||||
|
const bcrypt = require('bcryptjs');
|
||||||
|
const { app, pool } = require('../server');
|
||||||
|
|
||||||
|
test.after(async () => {
|
||||||
|
await pool.end();
|
||||||
|
});
|
||||||
|
|
||||||
|
let ipCounter = 0;
|
||||||
|
function nextIp() {
|
||||||
|
ipCounter += 1;
|
||||||
|
return `10.0.0.${ipCounter}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('repeated failed attempts for one account trip the account limiter even from different IPs', async () => {
|
||||||
|
const email = 'account-limit-test@example.test';
|
||||||
|
for (let i = 0; i < 5; i += 1) {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', nextIp())
|
||||||
|
.send({ email, password: 'wrong-password' });
|
||||||
|
assert.notEqual(res.status, 429);
|
||||||
|
}
|
||||||
|
const blocked = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', nextIp())
|
||||||
|
.send({ email, password: 'wrong-password' });
|
||||||
|
assert.equal(blocked.status, 429);
|
||||||
|
assert.equal(blocked.body.error, '尝试次数过多,请稍后重试');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('repeated failed attempts across many accounts from one IP trip the IP limiter', async () => {
|
||||||
|
const ip = nextIp();
|
||||||
|
for (let i = 0; i < 5; i += 1) {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', ip)
|
||||||
|
.send({ email: `rotating-${i}@example.test`, password: 'wrong-password' });
|
||||||
|
assert.notEqual(res.status, 429);
|
||||||
|
}
|
||||||
|
const blocked = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', ip)
|
||||||
|
.send({ email: 'rotating-final@example.test', password: 'wrong-password' });
|
||||||
|
assert.equal(blocked.status, 429);
|
||||||
|
assert.equal(blocked.body.error, '尝试次数过多,请稍后重试');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('successful logins are not counted against the auth limiters', async (t) => {
|
||||||
|
const email = 'success-test@example.test';
|
||||||
|
const password = 'correct horse battery staple';
|
||||||
|
const hash = await bcrypt.hash(password, 4);
|
||||||
|
|
||||||
|
t.mock.method(pool, 'query', async () => ({
|
||||||
|
rows: [{
|
||||||
|
id: 1,
|
||||||
|
email,
|
||||||
|
password_hash: hash,
|
||||||
|
username: 'tester',
|
||||||
|
avatar_url: '',
|
||||||
|
bio: '',
|
||||||
|
role: 'user',
|
||||||
|
signature: '',
|
||||||
|
}],
|
||||||
|
}));
|
||||||
|
|
||||||
|
const ip = nextIp();
|
||||||
|
for (let i = 0; i < 8; i += 1) {
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', ip)
|
||||||
|
.send({ email, password });
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing body fields fall back to the IP-only bucket without crashing', async () => {
|
||||||
|
const ip = nextIp();
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', ip)
|
||||||
|
.send({});
|
||||||
|
assert.equal(res.status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('malformed JSON bodies are rejected without crashing the server', async () => {
|
||||||
|
const ip = nextIp();
|
||||||
|
const res = await request(app)
|
||||||
|
.post('/api/auth/login')
|
||||||
|
.set('X-Forwarded-For', ip)
|
||||||
|
.set('Content-Type', 'application/json')
|
||||||
|
.send('{not valid json');
|
||||||
|
assert.equal(res.status, 400);
|
||||||
|
assert.equal(res.body.error, 'JSON 格式无效');
|
||||||
|
});
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
// schema.sql 与 migrations/ 是两套并存的表结构定义:
|
||||||
|
// - schema.sql 供安装脚本(install.sh)与手工部署直接执行
|
||||||
|
// - migrations/ 供 Docker entrypoint 与 npm run migrate 使用
|
||||||
|
//
|
||||||
|
// 两套定义必须产出等价的结构,否则「用脚本装的站」和「用迁移装的站」
|
||||||
|
// 会在后续升级中分化。历史上已经漂移过一次:001_initial.sql 漏掉了
|
||||||
|
// users.token_version 与 event_logs 的审计字段,导致登录后所有接口 500。
|
||||||
|
//
|
||||||
|
// 这里在文本层面断言两边覆盖同一批表与关键列,任何一边新增表或字段
|
||||||
|
// 却忘记同步另一边时立即失败。不依赖数据库连接,可直接在 CI 中运行。
|
||||||
|
|
||||||
|
const root = path.join(__dirname, '..');
|
||||||
|
const schemaSQL = fs.readFileSync(path.join(root, 'schema.sql'), 'utf8');
|
||||||
|
const migrationsDir = path.join(root, 'migrations');
|
||||||
|
const migrationSQL = fs.readdirSync(migrationsDir)
|
||||||
|
.filter(file => file.endsWith('.sql'))
|
||||||
|
.sort()
|
||||||
|
.map(file => fs.readFileSync(path.join(migrationsDir, file), 'utf8'))
|
||||||
|
.join('\n');
|
||||||
|
|
||||||
|
// 从 SQL 文本中收集被定义的表名(CREATE TABLE 与 ALTER TABLE 都算)。
|
||||||
|
function collectTables(sql) {
|
||||||
|
const tables = new Set();
|
||||||
|
const pattern = /(?:CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|ALTER\s+TABLE)\s+"?([a-z_][a-z0-9_]*)"?/gi;
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(sql)) !== null) tables.add(match[1].toLowerCase());
|
||||||
|
return tables;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集通过 ALTER TABLE <t> ADD COLUMN 追加的列,按表分组。
|
||||||
|
function collectAlteredColumns(sql) {
|
||||||
|
const added = new Map();
|
||||||
|
const pattern = /ALTER\s+TABLE\s+"?([a-z_][a-z0-9_]*)"?\s+ADD\s+COLUMN(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([a-z_][a-z0-9_]*)"?/gi;
|
||||||
|
let match;
|
||||||
|
while ((match = pattern.exec(sql)) !== null) {
|
||||||
|
const table = match[1].toLowerCase();
|
||||||
|
if (!added.has(table)) added.set(table, new Set());
|
||||||
|
added.get(table).add(match[2].toLowerCase());
|
||||||
|
}
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集 CREATE TABLE 块内声明的列。
|
||||||
|
function collectInlineColumns(sql) {
|
||||||
|
const declared = new Map();
|
||||||
|
const tablePattern = /CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([a-z_][a-z0-9_]*)"?\s*\(([\s\S]*?)\n\s*\);/gi;
|
||||||
|
let match;
|
||||||
|
while ((match = tablePattern.exec(sql)) !== null) {
|
||||||
|
const table = match[1].toLowerCase();
|
||||||
|
const body = match[2];
|
||||||
|
if (!declared.has(table)) declared.set(table, new Set());
|
||||||
|
for (const line of body.split('\n')) {
|
||||||
|
const trimmed = line.trim();
|
||||||
|
if (!trimmed || trimmed.startsWith('--')) continue;
|
||||||
|
// 跳过表级约束(PRIMARY KEY / UNIQUE / CHECK / FOREIGN KEY / CONSTRAINT)
|
||||||
|
if (/^(PRIMARY|UNIQUE|CHECK|FOREIGN|CONSTRAINT)\b/i.test(trimmed)) continue;
|
||||||
|
const columnMatch = trimmed.match(/^"?([a-z_][a-z0-9_]*)"?\s+[A-Za-z]/i);
|
||||||
|
if (columnMatch) declared.get(table).add(columnMatch[1].toLowerCase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return declared;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并「建表时声明」与「事后 ALTER 追加」两类列,得到每张表的完整列集合。
|
||||||
|
function collectColumns(sql) {
|
||||||
|
const columns = new Map();
|
||||||
|
const merge = source => {
|
||||||
|
for (const [table, cols] of source) {
|
||||||
|
if (!columns.has(table)) columns.set(table, new Set());
|
||||||
|
for (const col of cols) columns.get(table).add(col);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
merge(collectInlineColumns(sql));
|
||||||
|
merge(collectAlteredColumns(sql));
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
const schemaTables = collectTables(schemaSQL);
|
||||||
|
const migrationTables = collectTables(migrationSQL);
|
||||||
|
|
||||||
|
test('schema.sql and migrations define the same set of tables', () => {
|
||||||
|
const onlyInSchema = [...schemaTables].filter(t => !migrationTables.has(t));
|
||||||
|
const onlyInMigrations = [...migrationTables].filter(t => !schemaTables.has(t));
|
||||||
|
assert.deepEqual(
|
||||||
|
onlyInSchema, [],
|
||||||
|
`以下表只在 schema.sql 中定义,migrations/ 缺失:${onlyInSchema.join(', ')}`
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
onlyInMigrations, [],
|
||||||
|
`以下表只在 migrations/ 中定义,schema.sql 缺失:${onlyInMigrations.join(', ')}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schema.sql defines every column that migrations define', () => {
|
||||||
|
// schema.sql 是安装脚本实际执行的权威定义,迁移中出现过的列
|
||||||
|
// 必须都能在 schema.sql 里找到,否则脚本装出来的库会缺字段。
|
||||||
|
const migrationColumns = collectColumns(migrationSQL);
|
||||||
|
const schemaColumns = collectColumns(schemaSQL);
|
||||||
|
|
||||||
|
const missing = [];
|
||||||
|
for (const [table, cols] of migrationColumns) {
|
||||||
|
const schemaCols = schemaColumns.get(table);
|
||||||
|
if (!schemaCols) {
|
||||||
|
missing.push(`${table}.*(整张表缺失)`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const col of cols) {
|
||||||
|
if (!schemaCols.has(col)) missing.push(`${table}.${col}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert.deepEqual(
|
||||||
|
missing, [],
|
||||||
|
`schema.sql 缺少以下列,安装脚本建出的库将与迁移结果不一致:${missing.join(', ')}`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('columns required by server.js exist in both definitions', () => {
|
||||||
|
// server.js 直接查询、缺失即导致运行时 500 的列。
|
||||||
|
const REQUIRED = [
|
||||||
|
['users', 'token_version'],
|
||||||
|
['event_logs', 'method'],
|
||||||
|
['event_logs', 'path'],
|
||||||
|
['event_logs', 'user_agent'],
|
||||||
|
['event_logs', 'metadata'],
|
||||||
|
];
|
||||||
|
const schemaColumns = collectColumns(schemaSQL);
|
||||||
|
const migrationColumns = collectColumns(migrationSQL);
|
||||||
|
|
||||||
|
for (const [table, column] of REQUIRED) {
|
||||||
|
assert.ok(
|
||||||
|
schemaColumns.get(table)?.has(column),
|
||||||
|
`schema.sql 缺少 ${table}.${column}`
|
||||||
|
);
|
||||||
|
assert.ok(
|
||||||
|
migrationColumns.get(table)?.has(column),
|
||||||
|
`migrations/ 缺少 ${table}.${column}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schema.sql stays re-runnable for the installer update path', () => {
|
||||||
|
// install.sh 的自动更新会再次把整个 schema.sql 执行一遍,
|
||||||
|
// 因此其中的 DDL 必须全部写成幂等形式。
|
||||||
|
const createTables = schemaSQL.match(/CREATE\s+TABLE\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
|
||||||
|
assert.deepEqual(
|
||||||
|
createTables, [],
|
||||||
|
'schema.sql 存在未带 IF NOT EXISTS 的 CREATE TABLE,重复执行会失败'
|
||||||
|
);
|
||||||
|
const createIndexes = schemaSQL.match(/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
|
||||||
|
assert.deepEqual(
|
||||||
|
createIndexes, [],
|
||||||
|
'schema.sql 存在未带 IF NOT EXISTS 的 CREATE INDEX,重复执行会失败'
|
||||||
|
);
|
||||||
|
const addConstraints = schemaSQL.match(/ADD\s+CONSTRAINT\s+(?!IF\s+NOT\s+EXISTS)/gi) || [];
|
||||||
|
// ADD CONSTRAINT 在 PostgreSQL 中不支持 IF NOT EXISTS,需由守卫逻辑处理,
|
||||||
|
// 这里仅记录数量,避免误报。
|
||||||
|
assert.ok(addConstraints.length >= 0);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user