Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e7b0686947 | |||
| da72843c70 | |||
| 5598e1cbb7 | |||
| 46e0cdc0b3 | |||
| 8cfdfcbbf0 | |||
| 11f2131e4b | |||
| 7912b67ddc | |||
| 99c0f0319d | |||
| 3e98052c16 | |||
| ff2ab286fb |
2
.gitignore
vendored
@@ -8,6 +8,8 @@ out/
|
||||
.vercel/
|
||||
*.tsbuildinfo
|
||||
next-debug.log*
|
||||
# postbuild 抽取的字体声明(scripts/extract-font-css.mjs 生成)
|
||||
frontend/public/fonts/
|
||||
|
||||
# ===== Go 构建产物 =====
|
||||
*.exe
|
||||
|
||||
220
LICENSE
@@ -1,38 +1,202 @@
|
||||
姜十三论坛 专有软件许可协议
|
||||
Proprietary Software License Agreement
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
Copyright (c) 2026 姜十三. All Rights Reserved.
|
||||
版权所有 (c) 2026 姜十三。保留所有权利。
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
本软件(包括但不限于源代码、目标代码、文档、图像及其他随附资料,
|
||||
以下统称"本软件")由版权方(以下称"授权方")开发并所有。本软件
|
||||
以源码可见的方式发布,但这并不构成任何形式的开源授权。
|
||||
1. Definitions.
|
||||
|
||||
在未获得授权方事先书面许可之前,任何个人或组织不得:
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
1. 以任何目的(包括商业、内部生产、教学培训等)使用、运行或部署
|
||||
本软件的全部或任何部分;
|
||||
2. 复制、影印、转载、镜像、收录到任何数据库或以任何方式再现本软件;
|
||||
3. 修改、改编、翻译、合并、反向工程、反编译、反汇编本软件,或基于
|
||||
本软件创作衍生作品;
|
||||
4. 出售、出租、出借、分销、再许可、托管(SaaS)或以其他方式向第三方
|
||||
提供本软件或其任何副本;
|
||||
5. 删除、遮盖或更改本软件中的版权声明、商标或其他权利声明。
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
仅可出于个人学习、评估是否购买授权的目的浏览本仓库中的源代码;该等
|
||||
浏览不视为获得任何明示或默示的使用许可。
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
商业使用、内部部署或其他任何形式的使用授权,均须与授权方另行签订
|
||||
书面许可协议。
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
第三方开源组件按其各自附带的许可证条款授权,不受本协议约束。
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
本软件按"现状"(AS IS)提供,不附带任何明示或默示的担保,包括但不限
|
||||
于适销性、特定用途适用性或不侵权的担保。在任何情况下,授权方均不对因
|
||||
使用或无法使用本软件而导致的任何直接、间接、附带、特殊或后果性损害
|
||||
承担责任。
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
未经授权使用本软件的行为,均构成对授权方著作权及其他知识产权的侵犯,
|
||||
授权方保留依法追究法律责任的权利。
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
授权方联系方式:aarbbs@88.com
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that the copyright owner or their authorized
|
||||
representative conspicuously designates in writing as "Not a
|
||||
Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with the conditions
|
||||
stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides their Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The boilerplate notice should be enclosed in
|
||||
appropriate comment syntax for the file format. We also
|
||||
recommend that a file or class name and description of purpose be
|
||||
included on the same "printed page" as the copyright notice for
|
||||
easier identification within third-party archives.
|
||||
|
||||
Copyright 2026 姜十三
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
422
README.md
@@ -1,101 +1,128 @@
|
||||
<div align="center">
|
||||
|
||||
# 姜十三论坛(jiang13-bbs)
|
||||
|
||||
一个基于 Go + Next.js 的现代社区论坛系统,采用 SSR 直出 + HttpOnly Cookie 认证方案,具备完整的帖子/评论/通知/签到/管理后台功能。
|
||||
一个基于 **Go + Next.js** 构建的现代化社区论坛系统,SSR 直出、HttpOnly Cookie 认证,内置内容社区、代码片段、书库、积分体系、实时群聊与完整管理后台,开箱即用。
|
||||
|
||||
> **许可声明:** 本项目为专有软件(Proprietary),源码可见但不构成开源授权。详见 [LICENSE](./LICENSE)。未经书面许可,不得使用、部署或分发。
|
||||
[](./LICENSE)
|
||||
[](./VERSION)
|
||||
[](https://go.dev/)
|
||||
[](https://nextjs.org/)
|
||||
[](#贡献指南)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 目录
|
||||
|
||||
- [项目截图](#项目截图)
|
||||
- [功能特性](#功能特性)
|
||||
- [技术栈](#技术栈)
|
||||
- [快速开始](#快速开始)
|
||||
- [配置说明](#配置说明)
|
||||
- [Docker 部署](#docker-部署)
|
||||
- [项目结构](#项目结构)
|
||||
- [安全设计](#安全设计)
|
||||
- [开发与测试](#开发与测试)
|
||||
- [更新日志](#更新日志)
|
||||
- [贡献指南](#贡献指南)
|
||||
- [许可证](#许可证)
|
||||
- [联系方式](#联系方式)
|
||||
- [赞赏支持](#赞赏支持)
|
||||
|
||||
---
|
||||
|
||||
## 项目截图
|
||||
|
||||
| 首页信息流 | 帖子详情 |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
| 代码片段广场 | 书库在线阅读 |
|
||||
|  |  |
|
||||
| 管理后台仪表盘 | 访问统计分析 |
|
||||
|  |  |
|
||||
|
||||
<!--
|
||||
后台设置类截图(邮件 / 过滤 / 维护 / 安全 / 存储,含移动端与暗色模式):
|
||||
docs/screenshots/settings/
|
||||
-->
|
||||
|
||||
---
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 内容社区
|
||||
|
||||
- 帖子发布 / 编辑 / 删除,支持普通帖、**问答帖**(采纳答案、状态流转)、**投票帖**、**悬赏帖**、**抽奖帖**,以及密码帖与付费解锁内容
|
||||
- Markdown 写作与渲染:Shiki 代码高亮、目录导航、图片灯箱、视频/附件
|
||||
- 楼层化评论:主评论占楼层、子评论不占楼层,最多 10 层嵌套,单次查询拼装评论树,无 N+1
|
||||
- 评论与帖子均提供**编辑历史**、软删除与回收站(恢复 / 彻底删除)
|
||||
- 点赞、收藏、关注、置顶、推荐、锁定,联合唯一索引防止重复互动
|
||||
- 附件可设定积分价格,支持付费下载
|
||||
|
||||
### 积分与成长体系
|
||||
|
||||
- 每日签到 + 连续签到加成,积分余额与完整流水台账
|
||||
- 用户等级体系(经验值自动升级)与成就徽章(手动授予 / 自动通知)
|
||||
- 全站积分排行榜与个人排名
|
||||
|
||||
### 代码片段
|
||||
|
||||
- 独立的代码片段广场:多语言语法高亮、按语言筛选、全站统计
|
||||
- Fork、一键复制计数、片段评论、版本历史、可见性管理
|
||||
|
||||
### 书库 / 文档中心
|
||||
|
||||
- 书籍文档管理,两级章节(章 → 节)结构
|
||||
- 支持 **EPUB 解析导入**、Markdown 单篇 / 批量导入、整库导出与单本导出
|
||||
- 内置在线阅读器,封面、附件下载一应俱全
|
||||
|
||||
### 私信与群聊
|
||||
|
||||
- 一对一私信、多人群聊房间、默认全站大厅
|
||||
- 群成员管理:邀请 / 移出、禁言、角色设置;消息撤回、未读汇总、会话置顶
|
||||
|
||||
### 实时通知
|
||||
|
||||
- 评论、回复、点赞、@、系统通知等多类型站内消息
|
||||
- 未读红点 **SSR 首屏直出**,WebSocket 实时推送,页面回到前台时 HTTP 校准,支持单条 / 全部已读
|
||||
|
||||
### 管理后台
|
||||
|
||||
- 仪表盘与分析概览(Recharts 图表)
|
||||
- 内容审核队列(待审帖子 / 评论,板块管理员仅见授权板块)与内容回收站
|
||||
- 板块管理、版主授权、排序
|
||||
- 用户管理:角色、细粒度权限码、封禁、消息权限、登录日志、登录设备、积分调整
|
||||
- 公告文章、站点单页(CMS)管理
|
||||
- 广告位与赞助商配置(含用户自助购买提交、二维码、验证码)
|
||||
- 友情链接:用户申请、后台审批
|
||||
- 侧边栏可视化布局配置 + 自定义 HTML 小部件
|
||||
- 背景图、品牌 Logo 上传裁剪;全站媒体库盘点
|
||||
- **访问统计**:概览、实时、来源、页面、访客、安全、事件等多维度分析
|
||||
- 旧站数据导入(WordPress / Typecho 等)
|
||||
- 更新时间线:从 Git Commits / Releases 自动生成更新日志
|
||||
- 维护模式、系统诊断、SMTP 邮件配置(凭据加密存储)
|
||||
- 支持 S3 / MinIO 对象存储:文件内容去重、自适应图片变体、WebP 自动转换
|
||||
|
||||
### SEO
|
||||
|
||||
- 全站 SSR / ISR,title、description、OG 等关键内容均在初始 HTML 中
|
||||
- 帖子详情页输出 `DiscussionForumPosting` 类型 JSON-LD
|
||||
- 动态 `sitemap`、`robots`、Canonical 链接
|
||||
|
||||
---
|
||||
|
||||
## 技术栈
|
||||
|
||||
| 层级 | 技术 |
|
||||
|------|------|
|
||||
| 层级 | 技术选型 |
|
||||
|------|----------|
|
||||
| 后端 | Go 1.27 · Gin · GORM · PostgreSQL 17 |
|
||||
| 前端 | Next.js 16 (App Router) · TypeScript · Tailwind CSS v4 |
|
||||
| 认证 | JWT (HttpOnly Cookie) + Refresh Token 轮转 + CSRF 双提交 + Token Version 撤销 |
|
||||
| 部署 | 官方:`deploy/` Docker Compose(Next SSR + Go + Postgres,反代自备);本地开发仅 Compose 起数据库 |
|
||||
|
||||
---
|
||||
|
||||
## 功能概览
|
||||
|
||||
### 用户
|
||||
|
||||
- 注册 / 登录 / 登出(注册即登录,免二次跳转)
|
||||
- 个人资料编辑:昵称、头像、邮箱、个性签名
|
||||
- 修改密码(改密后全端踢下线)
|
||||
- 个人主页:发帖列表、评论列表(分页)、签到积分
|
||||
- 每日签到(积分 + 连续签到天数)
|
||||
|
||||
### 内容
|
||||
|
||||
- 帖子发帖 / 编辑 / 删除(作者本人或管理员)
|
||||
- 帖子类型:普通帖 / 问答帖
|
||||
- 帖子置顶 / 推荐(仅管理员)
|
||||
- 评论楼层制:主评论 = 楼层,子评论不占楼层,最多 10 层嵌套
|
||||
- 楼层分页 + 内存拼装评论树(单次查询,无 N+1)
|
||||
- Markdown 渲染(代码高亮、引用、列表等)
|
||||
- 帖子点赞(联合唯一索引防重复)
|
||||
|
||||
### 通知
|
||||
|
||||
- 站内通知:评论你的帖子、回复你的评论、点赞你的帖子
|
||||
- 未读红点 SSR 直出,实时靠 WebSocket 推送,回前台时 HTTP 校准
|
||||
- 单条标记已读 / 全部已读
|
||||
|
||||
### 管理后台
|
||||
|
||||
- 公告管理(草稿 / 发布、标签预设色)
|
||||
- 仪表盘
|
||||
|
||||
### SEO
|
||||
|
||||
- 全站 SSR/ISR,SEO 关键内容在初始 HTML 中
|
||||
- 帖子详情页输出 `DiscussionForumPosting` 类型 JSON-LD
|
||||
- 动态 `sitemap.ts` + `robots.ts`(由 Next.js 对外提供,后端不重复挂 `/sitemap.xml` / `/robots.txt`)
|
||||
|
||||
### 安全
|
||||
|
||||
- CSP / HSTS / X-Frame-Options: DENY / X-Content-Type-Options / Referrer-Policy
|
||||
- 速率限制:登录 20/min、注册 10/min、发帖新用户 24h 冷静期
|
||||
- Refresh Token 一次性轮转 + 盗用检测(吊销后重放 → 杀全家族)
|
||||
- 生产 HTTPS 启用 `__Host-` Cookie 前缀
|
||||
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
jiang13-bbs/
|
||||
├── backend/ # Go 后端
|
||||
│ ├── cmd/jiang13/ # 入口 main.go
|
||||
│ ├── config/ # 配置解析(app.ini + 环境变量)
|
||||
│ ├── handler/ # HTTP 处理器
|
||||
│ ├── middleware/ # 认证 / CSRF / 限流 / 安全头
|
||||
│ ├── model/ # GORM 模型 + 数据库初始化
|
||||
│ ├── router/ # 路由注册
|
||||
│ ├── service/ # 业务逻辑层
|
||||
│ ├── app.ini.example # 配置模板
|
||||
│ └── go.mod
|
||||
├── frontend/ # Next.js 前端
|
||||
│ ├── app/ # App Router 页面
|
||||
│ │ ├── settings/ # 账号设置(资料 + 密码)
|
||||
│ │ ├── u/[id]/ # 用户主页
|
||||
│ │ ├── post/[id]/ # 帖子详情
|
||||
│ │ ├── compose/ # 发帖
|
||||
│ │ ├── notifications/ # 通知列表
|
||||
│ │ ├── admin/ # 管理后台
|
||||
│ │ └── ...
|
||||
│ ├── components/ # 复用组件
|
||||
│ ├── lib/ # API 封装 / 工具函数
|
||||
│ ├── middleware.ts # SSR 登录态静默轮转
|
||||
│ ├── next.config.ts # Rewrite 代理 / 图片缓存
|
||||
│ └── .env.example
|
||||
├── deploy/ # 官方运行时(web + api + Postgres,反代自备)
|
||||
├── docker-compose.yml # 仅本地开发 Postgres
|
||||
├── LICENSE # 专有软件许可协议
|
||||
└── .gitignore
|
||||
```
|
||||
| 前端 | Next.js 16(App Router)· React 19 · TypeScript · Tailwind CSS v4 |
|
||||
| 认证 | JWT(HttpOnly Cookie)+ Refresh Token 轮转 + CSRF 双提交 + Token Version 撤销 |
|
||||
| 实时 | WebSocket(gorilla/websocket) |
|
||||
| 存储 | 本地存储 / S3(MinIO),Markdown 引擎 Goldmark,代码高亮 Shiki |
|
||||
| 部署 | Docker Compose:Next SSR + Go API + PostgreSQL(反向代理自备) |
|
||||
|
||||
---
|
||||
|
||||
@@ -104,8 +131,8 @@ jiang13-bbs/
|
||||
### 前置条件
|
||||
|
||||
- Go 1.27+
|
||||
- Node.js 20+ / pnpm 或 npm
|
||||
- PostgreSQL 17(或通过 Docker Compose 启动)
|
||||
- Node.js 20+(npm)
|
||||
- PostgreSQL 17(可通过 Docker Compose 启动)
|
||||
|
||||
### 1. 启动数据库
|
||||
|
||||
@@ -123,9 +150,9 @@ go mod download
|
||||
go run ./cmd/jiang13
|
||||
```
|
||||
|
||||
**工作目录必须是 `backend/`。** 上传文件与 JWT 密钥落在 `backend/data/`(头像 `backend/data/uploads/avatars/`)。不要在仓库根或 `backend/cmd/jiang13/` 执行 `go run`,否则会另建一套 data,数据库里头像 URL 会对不上文件。启动日志应含 `workPath=.../backend` 和 `dataDir=.../backend/data`。需要覆盖时设置 `JIANG13_WORK_PATH` 指向 `backend/`。
|
||||
> **工作目录必须是 `backend/`。** 上传文件与 JWT 密钥落在 `backend/data/`(头像位于 `backend/data/uploads/avatars/`)。在仓库根或 `backend/cmd/jiang13/` 下执行会另建一套 data,导致数据库中的文件 URL 对不上。启动日志应包含 `workPath=.../backend`;需要覆盖时可设置 `JIANG13_WORK_PATH`。
|
||||
|
||||
后端默认监听 `:3001`,首次启动自动执行数据库迁移并写入默认板块。同一时间只跑一个后端进程。
|
||||
后端默认监听 `:3001`,首次启动自动执行数据库迁移并写入默认板块。
|
||||
|
||||
### 3. 启动前端
|
||||
|
||||
@@ -136,13 +163,17 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端默认监听 `:3000`,通过 `next.config.ts` rewrite 将 `/api/*` 代理到后端。
|
||||
前端默认监听 `:3000`,通过 `next.config.ts` 的 rewrite 将 `/api/*` 代理到后端。
|
||||
|
||||
**空数据库首次注册的账号将自动成为站长。**
|
||||
|
||||
> Windows 用户也可直接使用仓库根目录的 `start.bat`(或 `start.sh`)一键启动开发环境,停止使用 `stop.bat` / `stop.sh`。
|
||||
|
||||
---
|
||||
|
||||
## 配置说明
|
||||
|
||||
### 后端(`backend/app.ini`)
|
||||
### 后端 `backend/app.ini`
|
||||
|
||||
```ini
|
||||
[server]
|
||||
@@ -152,108 +183,189 @@ HTTP_PORT = 3001
|
||||
DSN = postgres://postgres:postgres@localhost:5432/jiang13?sslmode=disable
|
||||
|
||||
[security]
|
||||
; 留空则自动生成并持久化到 data/.jwt_secret
|
||||
; 生产环境务必显式指定强随机值
|
||||
; 留空则自动生成并持久化到 data/.jwt_secret;生产环境务必显式指定强随机值
|
||||
JWT_SECRET =
|
||||
; 32 字节随机值的标准 Base64(openssl rand -base64 32),用于加密邮件 / S3 凭据
|
||||
SETTINGS_MASTER_KEY =
|
||||
|
||||
[paths]
|
||||
DATA = data
|
||||
|
||||
[app]
|
||||
DEV_MODE = true
|
||||
SITE_URL = http://localhost:3000
|
||||
CORS_ORIGINS =
|
||||
```
|
||||
|
||||
环境变量优先级高于 app.ini:`HTTP_PORT`、`DB_DSN`、`JWT_SECRET`、`DEV_MODE`。`JIANG13_WORK_PATH` 可强制指定后端根目录(`app.ini` 与 `data/` 所在处)。
|
||||
环境变量优先级高于 `app.ini`:`HTTP_PORT`、`DB_DSN`、`JWT_SECRET`、`SETTINGS_MASTER_KEY`、`DEV_MODE`、`SITE_URL`、`CORS_ORIGINS`、`TRUSTED_PROXIES`。
|
||||
|
||||
### 前端(`frontend/.env.local`)
|
||||
### 前端 `frontend/.env.local`
|
||||
|
||||
```bash
|
||||
# SSR 与 middleware 直连后端(本地开发)
|
||||
# SSR 与 middleware 直连后端
|
||||
NEXT_PUBLIC_API_URL=http://localhost:3001
|
||||
|
||||
# 部署到 Cloudflare Workers 等边缘环境时必须显式配置
|
||||
# 仅服务端可见;生产构建必须显式配置
|
||||
# BACKEND_URL=https://your-backend.example.com
|
||||
|
||||
# 与后端 DEV_MODE 对齐
|
||||
DEV_MODE=true
|
||||
```
|
||||
|
||||
完整环境变量清单见 [.env.example](./.env.example)、[frontend/.env.example](./frontend/.env.example)。
|
||||
|
||||
---
|
||||
|
||||
## Docker 部署
|
||||
|
||||
官方运行时位于 [`deploy/`](./deploy/),一体交付 **Next.js SSR + Go API + PostgreSQL 17**,不含反向代理(TLS 与同源路由由你的 Nginx / Caddy 处理)。
|
||||
|
||||
```bash
|
||||
cd deploy
|
||||
cp .env.example .env
|
||||
# 编辑 .env:POSTGRES_PASSWORD、JWT_SECRET、SITE_URL
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
然后将同一 Host 反向代理到容器:
|
||||
|
||||
- `/` → web `:3000`
|
||||
- `/api/`(含 `/api/ws`)、`/uploads/`、`/health` → api `:3001`
|
||||
|
||||
`GET https://你的域名/health` 返回 `{"status":"ok"}` 即部署成功。
|
||||
|
||||
详细说明、升级与备份命令见 [deploy/README.md](./deploy/README.md),Nginx 配置示例见 [deploy/nginx.example.conf](./deploy/nginx.example.conf),运行时契约见 [deploy/CONTRACT.md](./deploy/CONTRACT.md)。1Panel 面板部署可参考 [docs/deploy-1panel.md](./docs/deploy-1panel.md)。
|
||||
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
jiang13-bbs/
|
||||
├── backend/ # Go 后端
|
||||
│ ├── cmd/jiang13/ # 程序入口
|
||||
│ ├── config/ # 配置解析(app.ini + 环境变量)
|
||||
│ ├── handler/ # HTTP 处理器
|
||||
│ ├── middleware/ # 认证 / CSRF / 限流 / 安全头 / 访问捕获
|
||||
│ ├── model/ # GORM 模型与数据库初始化
|
||||
│ ├── realtime/ # WebSocket Hub
|
||||
│ ├── router/ # 路由注册
|
||||
│ ├── service/ # 业务逻辑层
|
||||
│ ├── markdown/ # Markdown 扩展(隐藏内容等)
|
||||
│ └── app.ini.example
|
||||
├── frontend/ # Next.js 前端
|
||||
│ ├── app/ # App Router 页面(含 admin 后台)
|
||||
│ ├── components/ # 通用组件
|
||||
│ ├── hooks/ # 自定义 Hooks
|
||||
│ ├── lib/ # API 封装与工具函数
|
||||
│ ├── public/ # 静态资源(表情图等)
|
||||
│ ├── middleware.ts # SSR 登录态静默轮转
|
||||
│ └── next.config.ts # Rewrite 代理 / 图片缓存
|
||||
├── deploy/ # 官方运行时(Docker Compose / Dockerfile)
|
||||
├── docs/ # 文档与截图
|
||||
├── docker-compose.yml # 本地开发用(仅 PostgreSQL)
|
||||
├── start.bat / start.sh # 本地一键启动
|
||||
├── VERSION
|
||||
└── LICENSE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 认证架构
|
||||
## 安全设计
|
||||
|
||||
采用三 Cookie + Token Version 方案,不使用 localStorage 存储 token:
|
||||
采用三 Cookie 方案,令牌不落 localStorage:
|
||||
|
||||
| Cookie | 用途 | 属性 |
|
||||
|--------|------|------|
|
||||
| `j13_token` | Access JWT(15 分钟) | HttpOnly · SameSite=Lax |
|
||||
| `j13_refresh` | Refresh Token(7 天,DB 存储 SHA-256) | HttpOnly · SameSite=Lax · Path=/ |
|
||||
| `j13_refresh` | Refresh Token(7 天,DB 存 SHA-256) | HttpOnly · SameSite=Lax · Path=/ |
|
||||
| `j13_csrf` | CSRF Token(JS 可读) | SameSite=Lax |
|
||||
|
||||
- **SSR 直出登录态:** `middleware.ts` 在页面/RSC 请求前本地解码 access token 的 exp,过期时静默调后端 refresh 轮转,新 cookie 注入请求头供 SSR 使用并透传浏览器。
|
||||
- **客户端续期:** `lib/api.ts` 的 `fetchWithRefresh` 遇到 401 自动调 `/api/auth/refresh` 重试。
|
||||
- **撤销机制:** 改密码 / 封禁 / 管理员强制下线时递增 `User.TokenVersion`,所有旧 JWT 立即失效。
|
||||
- **盗用检测:** Refresh Token 一次性轮转,已吊销 token 重放时撤销该用户全部 refresh token。
|
||||
|
||||
生产 HTTPS 下 cookie 名自动启用 `__Host-` 前缀。
|
||||
|
||||
若本机曾跑过早期构建,浏览器里可能还留着 `Path=/api/auth` 的 `j13_refresh`(HttpOnly,页面脚本删不掉)。打开开发者工具 → Application → Cookies,删掉该条,或对该源执行「清除站点数据」。之后只应存在 `Path=/` 的三枚 cookie。
|
||||
- **SSR 直出登录态**:`middleware.ts` 在渲染前检查 Access Token 过期时间,过期则静默轮转,新 Cookie 同时供 SSR 使用并透传浏览器
|
||||
- **Refresh Token 一次性轮转 + 盗用检测**:已吊销 Token 被重放时,撤销该用户全部 Refresh Token
|
||||
- **Token Version 撤销**:改密 / 封禁 / 强制下线时递增版本号,旧 JWT 立即失效
|
||||
- **速率限制**:登录、注册、发帖(新用户 24h 冷静期)、评论、上传等分级限流,管理员豁免
|
||||
- **安全响应头**:CSP、HSTS、X-Frame-Options: DENY、X-Content-Type-Options、Referrer-Policy
|
||||
- 生产 HTTPS 下 Cookie 自动启用 `__Host-` 前缀,要求前后端必须**同源部署**(不能拆分到子域)
|
||||
|
||||
---
|
||||
|
||||
## 部署
|
||||
|
||||
**官方运行时是 `deploy/docker-compose.yml`(Next SSR + Go + Postgres,不含反代)。** 说明与升级命令见 [deploy/README.md](./deploy/README.md),Nginx 示例见 [deploy/nginx.example.conf](./deploy/nginx.example.conf),契约见 [deploy/CONTRACT.md](./deploy/CONTRACT.md)。
|
||||
|
||||
本地开发仍用仓库根 `start.bat` / `start.sh` 与根目录 `docker-compose.yml`(只起 Postgres)。不要把开发流程改成必须打应用镜像。
|
||||
|
||||
更新应用(镜像已发布时):
|
||||
## 开发与测试
|
||||
|
||||
```bash
|
||||
cd deploy
|
||||
docker compose pull
|
||||
docker compose up -d
|
||||
# 后端测试
|
||||
cd backend && go test ./...
|
||||
|
||||
# 前端测试(Node 内置 test runner)
|
||||
cd frontend && npm test
|
||||
|
||||
# 前端代码检查
|
||||
npm run lint
|
||||
```
|
||||
|
||||
后台一键更新、预编译包不在本期。Cloudflare Workers 不是官方运行时。
|
||||
开发约定:
|
||||
|
||||
### 生产环境要点
|
||||
|
||||
1. **官方 Compose:** `DEV_MODE=false`,强随机 `JWT_SECRET` 与 `POSTGRES_PASSWORD`;由你现有的 Nginx/Caddy 提供 HTTPS,并把页面与 `/api`、`/api/ws`、`/uploads` 挂到同一 Host。
|
||||
2. **CORS 与 Canonical:** 设 `SITE_URL` 为对外 origin(不要改 `router.go` 写死域名)。官方 Compose 会同时注入 api 与 web;web 用它生成 Canonical / sitemap,不要填 `http://api:3001`。
|
||||
3. **自管部署:** 仍须同源反代。Workers 前端须保持 `middleware.ts` 文件名(OpenNext 不识别 `proxy.ts`),实时通道由反代承接 `/api/ws`。
|
||||
|
||||
### WebSocket(开发 vs 生产)
|
||||
|
||||
浏览器发起 WebSocket 握手**一定会带 `Origin`**。后端拒绝空 Origin,这只挡住 curl / 脚本探测,**不影响 `npm run dev`,也不影响生产浏览器**。
|
||||
|
||||
**开发环境(`DEV_MODE=true`)**
|
||||
|
||||
- 页面在 `http://localhost:3000`,WS 直连 `ws://localhost:3001/api/ws`(Next.js rewrite 不透传 `Upgrade`)。
|
||||
- 二者端口不同,不是浏览器意义上的同源。后端因此放行 Origin 主机为 `localhost` / `127.0.0.1` 的**任意端口**。
|
||||
- Cookie 不按端口隔离,`:3000` 上的 `j13_token` 会随握手带到 `:3001`。不要把 `DEV_MODE` 改成 `false` 再跑这对端口,否则 Origin `localhost:3000` 对不上 Host `localhost:3001`,握手会被拒。
|
||||
|
||||
**生产环境(`DEV_MODE=false`)**
|
||||
|
||||
- Origin 的 host(含端口)必须与请求 `Host` **完全一致**。请用 Nginx/Caddy 把前端与 `/api/`、`/api/ws` 挂到同一域名,例如 `https://bbs.example.com`。
|
||||
- 反向代理需透传 `Upgrade`、`Connection`,并保留原始 `Host` / `Origin`。
|
||||
- 生产 cookie 使用 `__Host-` 前缀,要求 `Secure`、`Path=/`、**不能设 Domain**。因此 API **不能**放到 `api.example.com` 这类另一子域,否则登录 cookie 与 WS 都会失效。
|
||||
- Cloudflare Workers / OpenNext **不能**透传任意 WebSocket。若前端部署在 Workers,实时通道必须由同源反代(Nginx 等)承接 `/api/ws`,而不是指望 Workers 升级连接。
|
||||
- 可用 `NEXT_PUBLIC_WS_URL` 覆盖前端连线地址;一旦覆盖,Origin 仍须与后端看到的 Host 一致。
|
||||
- Next.js 16 中 `params` / `searchParams` / `cookies()` / `headers()` 均需 `await`
|
||||
- 权限校验只在 Go 后端执行,前端不做判定
|
||||
- 配色仅修改 `frontend/app/globals.css` 中的 CSS 令牌,不在组件内硬编码颜色
|
||||
- 所有公开页面保持 SSR / ISR,SEO 关键内容必须在初始 HTML 中
|
||||
|
||||
---
|
||||
|
||||
## 开发约定
|
||||
## 更新日志
|
||||
|
||||
- **Next.js 16:** `params` / `searchParams` / `cookies()` / `headers()` 必须 `await`。
|
||||
- **SEO:** 所有公开页面 SSR/ISR,SEO 关键内容(title、description、OG、JSON-LD)必须在初始 HTML 中。
|
||||
- **权限:** 权限校验只在 Go 后端执行,前端不做判定。
|
||||
- **配色:** 仅修改 `frontend/app/globals.css` 中的 CSS 令牌,禁止在组件内硬编码颜色。
|
||||
- **无障碍:** 文字对比度 ≥4.5:1,交互控件边界 ≥3:1(WCAG 2.1 AA)。
|
||||
版本发布与部署契约变更记录见 [deploy/CHANGELOG.md](./deploy/CHANGELOG.md),当前版本 **v0.2.9**。
|
||||
|
||||
---
|
||||
|
||||
## 贡献指南
|
||||
|
||||
欢迎提交 Issue 与 Pull Request!
|
||||
|
||||
1. Fork 本仓库并创建特性分支:`git checkout -b feature/your-feature`
|
||||
2. 提交前请确保测试通过:后端 `go test ./...`,前端 `npm test`
|
||||
3. 提交代码并推送分支
|
||||
4. 在 GitHub 上发起 Pull Request,描述清楚改动内容与动机
|
||||
|
||||
- 提交信息建议遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范(`feat:` / `fix:` / `docs:` 等)
|
||||
- 发现安全问题请**不要**直接提 Issue,发送邮件至 aarbbs@88.com 私下反馈
|
||||
|
||||
---
|
||||
|
||||
## 许可证
|
||||
|
||||
**专有软件(Proprietary)** — Copyright © 2026 姜十三,保留所有权利。
|
||||
本项目基于 [Apache License 2.0](./LICENSE) 开源。
|
||||
|
||||
源码仅可见,未经书面许可不得使用、部署、修改或分发。详见 [LICENSE](./LICENSE)。
|
||||
```
|
||||
Copyright 2026 姜十三
|
||||
|
||||
联系方式:aarbbs@88.com
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 联系方式
|
||||
|
||||
- QQ:97975089
|
||||
|
||||
- 邮箱:97975089@qq.com
|
||||
|
||||
- Issue:[GitHub Issues](https://github.com/aarbbs/jiang13-bbs/issues)
|
||||
|
||||
---
|
||||
|
||||
## 赞赏支持
|
||||
|
||||
如果本项目对你有帮助,欢迎请作者喝杯咖啡 ☕,你的支持是持续维护的动力。
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/wechat.png" width="220" alt="微信打赏" />
|
||||
|
||||
<img src="docs/images/zfb.png" width="220" alt="支付宝打赏" />
|
||||
</p>
|
||||
|
||||
<p align="center">微信打赏 | 支付宝打赏</p>
|
||||
|
||||
@@ -257,7 +257,7 @@ func TestEnsureAppIniBackfillsMissingKeys(t *testing.T) {
|
||||
|
||||
func TestParseSiteURLFromIni(t *testing.T) {
|
||||
work := t.TempDir()
|
||||
body := "[security]\nJWT_SECRET = "+testJWTSecret+"\n\n[app]\nDEV_MODE = true\nSITE_URL = https://forum.example.com/\nCORS_ORIGINS = https://a.example.com, https://b.example.com/\n"
|
||||
body := "[security]\nJWT_SECRET = " + testJWTSecret + "\n\n[app]\nDEV_MODE = true\nSITE_URL = https://forum.example.com/\nCORS_ORIGINS = https://a.example.com, https://b.example.com/\n"
|
||||
if err := os.WriteFile(filepath.Join(work, "app.ini"), []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ func optionalLegacyZip(c *gin.Context, field, pattern, label string) (string, bo
|
||||
return "", true // 字段不存在,视为未上传
|
||||
}
|
||||
if fh.Size > service.LegacyZipMaxBytes {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": label+"不能超过 128MB"})
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": label + "不能超过 128MB"})
|
||||
return "", false
|
||||
}
|
||||
path, err := saveMultipartToTemp(fh, pattern)
|
||||
|
||||
@@ -94,6 +94,41 @@ func (h *Handlers) AdminSetUserMessages(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"user": user})
|
||||
}
|
||||
|
||||
// AdminGetUserPerms 读取账号级渠道权限(超管/站长,授权弹窗回显用)
|
||||
func (h *Handlers) AdminGetUserPerms(c *gin.Context) {
|
||||
id, ok := parseAdminUserID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
perms, err := h.AdminUser.GetPermOverrides(middleware.CurrentActor(c), id)
|
||||
if err != nil {
|
||||
respondAdminUserError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"perm_overrides": perms})
|
||||
}
|
||||
|
||||
// AdminSetUserPerms 授予/撤销账号级渠道权限(超管/站长)
|
||||
func (h *Handlers) AdminSetUserPerms(c *gin.Context) {
|
||||
id, ok := parseAdminUserID(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Perms []string `json:"perms"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
user, err := h.AdminUser.SetPermOverrides(middleware.CurrentActor(c), id, body.Perms)
|
||||
if err != nil {
|
||||
respondAdminUserError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"user": user})
|
||||
}
|
||||
|
||||
// AdminSetUserBan 封禁 / 解封用户
|
||||
func (h *Handlers) AdminSetUserBan(c *gin.Context) {
|
||||
id, ok := parseAdminUserID(c)
|
||||
|
||||
@@ -382,8 +382,11 @@ func meUserBody(user *model.User, boardIDs []uint, badges []model.UserBadge) gin
|
||||
"role": user.Role,
|
||||
"board_ids": boardIDs,
|
||||
"can_manage_messages": user.CanManageMessages,
|
||||
"level": user.Level,
|
||||
"total_points": user.TotalPoints,
|
||||
// 生效权限码(角色默认 ∪ 账号级渠道授予):前端据此渲染后台入口/按钮,
|
||||
// 最终权限以后端 RequirePerm 校验为准
|
||||
"perms": service.EffectivePerms(user.Role, user.PermOverrides, user.CanManageMessages),
|
||||
"level": user.Level,
|
||||
"total_points": user.TotalPoints,
|
||||
}
|
||||
if badges != nil {
|
||||
body["badges"] = badges
|
||||
|
||||
@@ -51,11 +51,11 @@ func (h *Handlers) BoardSidebar(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"board": data.Board,
|
||||
"moderators": data.Moderators,
|
||||
"stats": data.Stats,
|
||||
"hot": data.Hot,
|
||||
"active_users": data.ActiveUsers,
|
||||
"checkin": data.Checkin,
|
||||
"board": data.Board,
|
||||
"moderators": data.Moderators,
|
||||
"stats": data.Stats,
|
||||
"hot": data.Hot,
|
||||
"active_users": data.ActiveUsers,
|
||||
"checkin": data.Checkin,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
@@ -42,6 +44,26 @@ func chatRoomID(c *gin.Context) (uint, bool) {
|
||||
return uint(id), true
|
||||
}
|
||||
|
||||
// formatMuteDurationCN 禁言时长中文格式化,供系统提示消息使用
|
||||
func formatMuteDurationCN(minutes int) string {
|
||||
switch {
|
||||
case minutes >= 30*24*60:
|
||||
return "30 天"
|
||||
case minutes >= 7*24*60:
|
||||
return "7 天"
|
||||
case minutes >= 3*24*60:
|
||||
return "3 天"
|
||||
case minutes >= 24*60:
|
||||
return "1 天"
|
||||
case minutes >= 12*60:
|
||||
return "12 小时"
|
||||
case minutes >= 60:
|
||||
return "1 小时"
|
||||
default:
|
||||
return strconv.Itoa(minutes) + " 分钟"
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handlers) chatOversee(userID uint) bool {
|
||||
actor, err := h.Auth.LoadActor(userID)
|
||||
if err != nil || actor == nil {
|
||||
@@ -219,11 +241,32 @@ func (h *Handlers) JoinChatRoom(c *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
_, _, err := h.Chat.Join(claims.ID, roomID)
|
||||
member, joined, err := h.Chat.Join(claims.ID, roomID)
|
||||
if err != nil {
|
||||
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
// 首次加入则向房间广播系统提示 + 成员变更
|
||||
if joined && member != nil {
|
||||
displayName := h.Chat.DisplayName(claims.ID)
|
||||
if displayName != "" {
|
||||
sysMsg, _ := h.Chat.SendSystemMessage(roomID, displayName+" 加入了群聊")
|
||||
if sysMsg != nil && sysMsg.ID > 0 {
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMessage,
|
||||
Data: sysMsg,
|
||||
})
|
||||
}
|
||||
}
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMembership,
|
||||
Data: gin.H{
|
||||
"room_id": roomID,
|
||||
"status": "joined",
|
||||
"user_id": claims.ID,
|
||||
},
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
@@ -279,6 +322,35 @@ func (h *Handlers) InviteChatMembers(c *gin.Context) {
|
||||
Data: gin.H{"room_id": roomID, "status": "invited"},
|
||||
})
|
||||
}
|
||||
// 被邀请者入群时向房间广播系统提示 + 成员变更
|
||||
if len(added) > 0 {
|
||||
var names []string
|
||||
for _, uid := range added {
|
||||
if n := h.Chat.DisplayName(uid); n != "" {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
if len(names) > 0 {
|
||||
content := strings.Join(names, "、") + " 加入了群聊"
|
||||
sysMsg, _ := h.Chat.SendSystemMessage(roomID, content)
|
||||
if sysMsg != nil && sysMsg.ID > 0 {
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMessage,
|
||||
Data: sysMsg,
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, uid := range added {
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMembership,
|
||||
Data: gin.H{
|
||||
"room_id": roomID,
|
||||
"status": "joined",
|
||||
"user_id": uid,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"added": added})
|
||||
}
|
||||
|
||||
@@ -322,7 +394,7 @@ func (h *Handlers) KickChatMember(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// SetChatMemberMute 禁言/解禁成员
|
||||
// SetChatMemberMute 禁言/解禁成员;duration_minutes 可选:0/缺省=永久,>0=指定分钟数
|
||||
func (h *Handlers) SetChatMemberMute(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
roomID, ok := chatRoomID(c)
|
||||
@@ -335,17 +407,58 @@ func (h *Handlers) SetChatMemberMute(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Muted bool `json:"muted"`
|
||||
Muted bool `json:"muted"`
|
||||
DurationMinutes int `json:"duration_minutes"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
if err := h.Chat.SetMemberMute(claims.ID, roomID, uint(targetID), body.Muted, h.chatOversee(claims.ID)); err != nil {
|
||||
duration := time.Duration(body.DurationMinutes) * time.Minute
|
||||
targetName, err := h.Chat.SetMemberMute(claims.ID, roomID, uint(targetID), body.Muted, duration, h.chatOversee(claims.ID))
|
||||
if err != nil {
|
||||
c.JSON(chatErrToStatus(err), gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true, "muted": body.Muted})
|
||||
// 向房间内广播禁言/解禁事件,客户端据此更新输入框状态与成员列表
|
||||
var mutedUntil *time.Time
|
||||
if body.Muted && body.DurationMinutes > 0 {
|
||||
t := time.Now().Add(duration)
|
||||
mutedUntil = &t
|
||||
}
|
||||
// 落库一条系统提示消息,刷新后仍可见(走 SendSystemMessage 统一处理房间 last_message_id 等)
|
||||
var sysContent string
|
||||
if body.Muted {
|
||||
if body.DurationMinutes > 0 {
|
||||
sysContent = targetName + " 已被禁言 " + formatMuteDurationCN(body.DurationMinutes)
|
||||
} else {
|
||||
sysContent = targetName + " 已被禁言 永久"
|
||||
}
|
||||
} else {
|
||||
sysContent = targetName + " 的禁言已被解除"
|
||||
}
|
||||
sysMsg, _ := h.Chat.SendSystemMessage(roomID, sysContent)
|
||||
// 广播系统消息到房间(sender_id=0,前端按系统消息渲染);
|
||||
// Data 与普通消息一致直接放消息体(扁平结构),前端按 room_id 匹配后才能即时上屏
|
||||
if sysMsg != nil && sysMsg.ID > 0 {
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMessage,
|
||||
Data: sysMsg,
|
||||
})
|
||||
}
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
|
||||
Type: realtime.EventChatMemberMuted,
|
||||
Data: gin.H{
|
||||
"room_id": roomID,
|
||||
"user_id": uint(targetID),
|
||||
"muted": body.Muted,
|
||||
"muted_until": mutedUntil,
|
||||
"duration_minutes": body.DurationMinutes,
|
||||
"target_name": targetName,
|
||||
"operator_id": claims.ID,
|
||||
},
|
||||
})
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true, "muted": body.Muted, "duration_minutes": body.DurationMinutes})
|
||||
}
|
||||
|
||||
// SetChatMemberRole 站长任命/撤销群管理员
|
||||
@@ -619,7 +732,9 @@ func (h *Handlers) broadcastChatRecalled(roomID uint, msg *model.ChatMessage, ne
|
||||
}
|
||||
env := realtime.Envelope{Type: realtime.EventChatRecalled, Data: data}
|
||||
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), env)
|
||||
// 未订阅该房间的成员(侧栏在看别的会话)也需要实时改预览
|
||||
// 未订阅该房间的成员(侧栏在看别的会话)也需要实时改预览:
|
||||
// 已撤回正文不得残留在侧栏预览里。预览回滚到上一条真实消息由 RecallMessage
|
||||
// 回退 last_message_id 完成,本推送只负责即时抹掉正文、不产生角标与置顶。
|
||||
if h.Chat == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -82,38 +82,6 @@ func (h *Handlers) PostComments(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// CommentLocation 评论定位:返回该评论的楼层号(含软删占位,与楼层分页口径一致),
|
||||
// 供通知/主页评论深链 #comment-{id} 跨页时换到正确页码。0 楼 = 评论不存在。
|
||||
func (h *Handlers) CommentLocation(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的帖子 ID"})
|
||||
return
|
||||
}
|
||||
cid, err := strconv.ParseUint(c.Param("cid"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
|
||||
return
|
||||
}
|
||||
// 待审/被拒帖子的评论不对公众开放
|
||||
var viewerID uint
|
||||
var loadActor func() *service.Actor
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
viewerID = claims.ID
|
||||
loadActor = h.actorLoader(claims.ID)
|
||||
}
|
||||
if err := h.Post.EnsurePostVisible(uint(id), viewerID, loadActor); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "帖子不存在"})
|
||||
return
|
||||
}
|
||||
floor := h.Comment.FloorNumber(uint(id), uint(cid))
|
||||
if floor <= 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "评论不存在"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"floor": floor})
|
||||
}
|
||||
|
||||
// CreateCommentRequest 评论请求
|
||||
type CreateCommentRequest struct {
|
||||
Content string `json:"content" binding:"required,min=1,max=5000"`
|
||||
|
||||
@@ -10,38 +10,39 @@ import (
|
||||
|
||||
// Handlers 聚合所有服务引用
|
||||
type Handlers struct {
|
||||
Ops *service.Operations
|
||||
Cfg *config.Config
|
||||
Hub *realtime.Hub
|
||||
Auth *service.AuthService
|
||||
Board *service.BoardService
|
||||
Post *service.PostService
|
||||
Comment *service.CommentService
|
||||
Like *service.LikeService
|
||||
Favorite *service.FavoriteService
|
||||
Follow *service.FollowService
|
||||
Notification *service.NotificationService
|
||||
OverviewSvc *service.OverviewService
|
||||
Checkin *service.CheckinService
|
||||
Announcement *service.AnnouncementService
|
||||
SitePage *service.SitePageService
|
||||
Upload *service.UploadService
|
||||
PostFile *service.PostFileService
|
||||
Points *service.PointsService
|
||||
Setting *service.SettingService
|
||||
AdminUser *service.AdminUserService
|
||||
LegacyImport *service.LegacyImportService
|
||||
Moderation *service.ModerationService
|
||||
Chat *service.ChatService
|
||||
Visit *service.VisitStatsService
|
||||
Analytics *service.AnalyticsService
|
||||
HidePwd *service.HidePasswordCookie
|
||||
Ads *service.AdService
|
||||
Sidebar *service.SidebarService
|
||||
FriendLink *service.FriendLinkService
|
||||
Badge *service.BadgeService
|
||||
Ops *service.Operations
|
||||
Cfg *config.Config
|
||||
Hub *realtime.Hub
|
||||
Auth *service.AuthService
|
||||
Board *service.BoardService
|
||||
Post *service.PostService
|
||||
Comment *service.CommentService
|
||||
Like *service.LikeService
|
||||
Favorite *service.FavoriteService
|
||||
Follow *service.FollowService
|
||||
Notification *service.NotificationService
|
||||
OverviewSvc *service.OverviewService
|
||||
Checkin *service.CheckinService
|
||||
Announcement *service.AnnouncementService
|
||||
SitePage *service.SitePageService
|
||||
Upload *service.UploadService
|
||||
PostFile *service.PostFileService
|
||||
Points *service.PointsService
|
||||
Setting *service.SettingService
|
||||
AdminUser *service.AdminUserService
|
||||
LegacyImport *service.LegacyImportService
|
||||
Moderation *service.ModerationService
|
||||
Chat *service.ChatService
|
||||
Visit *service.VisitStatsService
|
||||
Analytics *service.AnalyticsService
|
||||
HidePwd *service.HidePasswordCookie
|
||||
Ads *service.AdService
|
||||
Sidebar *service.SidebarService
|
||||
FriendLink *service.FriendLinkService
|
||||
Badge *service.BadgeService
|
||||
LeaderboardSvc *service.LeaderboardService
|
||||
LibrarySvc *service.LibraryService
|
||||
SnippetSvc *service.SnippetService
|
||||
}
|
||||
|
||||
// resolvePublishStatus 决定新帖/新评的初始状态:
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
@@ -91,7 +92,11 @@ func (h *Handlers) AdminCreateLibraryDoc(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
d, err := h.LibrarySvc.Create(&in)
|
||||
var creatorID uint
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
creatorID = claims.ID
|
||||
}
|
||||
d, err := h.LibrarySvc.Create(&in, creatorID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -242,6 +247,109 @@ func (h *Handlers) AdminDeleteLibraryFile(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// ---------- 管理端:导出(迁移 / 备份) ----------
|
||||
|
||||
// writeLibraryExport 装载完成后统一以附件形式流式下发 ZIP;
|
||||
// 注:一旦开始写响应体,中途 IO 错误无法再改成 JSON 错误,只能记录在 c.Errors。
|
||||
func (h *Handlers) writeLibraryExport(c *gin.Context, exp *service.LibraryExport) {
|
||||
c.Header("Content-Type", "application/zip")
|
||||
c.Header("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(exp.Filename))
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Status(http.StatusOK)
|
||||
if err := exp.WriteZip(c.Writer); err != nil {
|
||||
_ = c.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
// AdminExportLibraryDoc 导出单本书(元信息 + 章节 + 附件 + 本地封面,ZIP)
|
||||
func (h *Handlers) AdminExportLibraryDoc(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的条目 ID"})
|
||||
return
|
||||
}
|
||||
exp, err := h.LibrarySvc.BuildBookExport(uint(id))
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrLibraryNotFound) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "条目不存在"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "导出失败"})
|
||||
return
|
||||
}
|
||||
h.writeLibraryExport(c, exp)
|
||||
}
|
||||
|
||||
// AdminExportAllLibrary 导出全部在用书籍(单 ZIP,library.json 索引)
|
||||
func (h *Handlers) AdminExportAllLibrary(c *gin.Context) {
|
||||
exp, err := h.LibrarySvc.BuildAllExport()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "导出失败"})
|
||||
return
|
||||
}
|
||||
h.writeLibraryExport(c, exp)
|
||||
}
|
||||
|
||||
// AdminImportLibrary 上传导出 ZIP 恢复书籍(mode=create 默认跳过冲突 / overwrite 覆盖同名)
|
||||
func (h *Handlers) AdminImportLibrary(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
|
||||
const overhead = 64 << 10 // multipart 边界开销
|
||||
limit := int64(service.LibraryImportMaxBytes) + overhead
|
||||
if c.Request.ContentLength > limit {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "导入包过大"})
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
|
||||
|
||||
fh, err := c.FormFile("file")
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "导入包过大(不能超过 512MB)"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请选择书库导出的 ZIP 备份包"})
|
||||
return
|
||||
}
|
||||
if fh.Size > service.LibraryImportMaxBytes {
|
||||
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "导入包不能超过 512MB"})
|
||||
return
|
||||
}
|
||||
|
||||
mode := c.PostForm("mode")
|
||||
if mode == "" {
|
||||
mode = service.LibraryImportModeCreate
|
||||
}
|
||||
|
||||
tmpPath, err := saveMultipartToTemp(fh, "library-import-*.zip")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "读取导入包失败"})
|
||||
return
|
||||
}
|
||||
defer os.Remove(tmpPath)
|
||||
|
||||
rep, err := h.LibrarySvc.ImportLibraryZip(tmpPath, mode, claims.ID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrLibraryImportBadZip),
|
||||
errors.Is(err, service.ErrLibraryImportFormat),
|
||||
errors.Is(err, service.ErrLibraryImportVer),
|
||||
errors.Is(err, service.ErrLibraryImportEmpty),
|
||||
errors.Is(err, service.ErrLibraryImportMode):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "导入失败:" + err.Error()})
|
||||
}
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"report": rep})
|
||||
}
|
||||
|
||||
// ---------- 管理端:章节 ----------
|
||||
|
||||
// AdminCreateLibrarySection 新建章节(parent_id 空=章,非空=节)
|
||||
|
||||
@@ -5,9 +5,18 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// notificationView 通知列表项:附带关联评论的楼层相对锚点,
|
||||
// 供前端拼 #comment-{floor}(主楼)或 #comment-{floor}-r{comment_id}(楼中楼)。
|
||||
type notificationView struct {
|
||||
*model.Notification
|
||||
CommentFloor uint `json:"comment_floor"`
|
||||
CommentIsRoot bool `json:"comment_is_root"`
|
||||
}
|
||||
|
||||
// Notifications 获取当前用户的通知列表(分页)
|
||||
func (h *Handlers) Notifications(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
@@ -19,8 +28,24 @@ func (h *Handlers) Notifications(c *gin.Context) {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
commentIDs := make([]uint, 0, len(list))
|
||||
for _, n := range list {
|
||||
if n.CommentID > 0 {
|
||||
commentIDs = append(commentIDs, n.CommentID)
|
||||
}
|
||||
}
|
||||
anchors := h.Comment.AnchorsByCommentIDs(commentIDs)
|
||||
views := make([]notificationView, 0, len(list))
|
||||
for i := range list {
|
||||
v := notificationView{Notification: &list[i]}
|
||||
if a, ok := anchors[list[i].CommentID]; ok {
|
||||
v.CommentFloor = a.Floor
|
||||
v.CommentIsRoot = a.IsRoot
|
||||
}
|
||||
views = append(views, v)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"notifications": nonNilSlice(list),
|
||||
"notifications": nonNilSlice(views),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
|
||||
@@ -262,6 +262,10 @@ func (h *Handlers) SendEmailCode(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
wait, e := h.Ops.SendCode(req.Email, req.Purpose, c.ClientIP())
|
||||
if errors.Is(e, service.ErrEmailRegistered) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": e.Error()})
|
||||
return
|
||||
}
|
||||
if !h.quotaResponse(c, wait, e) {
|
||||
return
|
||||
}
|
||||
@@ -313,7 +317,8 @@ func (h *Handlers) PublicObject(c *gin.Context) {
|
||||
defer r.Close()
|
||||
c.Header("Content-Type", m)
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
c.Header("Cache-Control", "private, no-store")
|
||||
// 对象 ID 按上传随机生成不覆盖,直出内容可短缓存(302 预签名分支不缓存,防过期地址复用)
|
||||
c.Header("Cache-Control", "public, max-age=86400")
|
||||
c.Status(200)
|
||||
_, _ = io.Copy(c.Writer, r)
|
||||
}
|
||||
|
||||
@@ -29,20 +29,20 @@ func (h *Handlers) Overview(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"stats": data.Stats,
|
||||
"hot": data.Hot,
|
||||
"active_users": data.ActiveUsers,
|
||||
"boards": data.Boards,
|
||||
"announcements": data.Announcements,
|
||||
"announcements_total": data.AnnouncementsTotal,
|
||||
"sidebar_pages": data.SidebarPages,
|
||||
"new_users": data.NewUsers,
|
||||
"checkin": data.Checkin,
|
||||
"ads": data.Ads,
|
||||
"ads_panel_title": data.AdsPanelTitle,
|
||||
"ads_enabled": data.AdsEnabled,
|
||||
"sponsors": data.Sponsors,
|
||||
"stats": data.Stats,
|
||||
"hot": data.Hot,
|
||||
"active_users": data.ActiveUsers,
|
||||
"boards": data.Boards,
|
||||
"announcements": data.Announcements,
|
||||
"announcements_total": data.AnnouncementsTotal,
|
||||
"sidebar_pages": data.SidebarPages,
|
||||
"new_users": data.NewUsers,
|
||||
"checkin": data.Checkin,
|
||||
"ads": data.Ads,
|
||||
"ads_panel_title": data.AdsPanelTitle,
|
||||
"ads_enabled": data.AdsEnabled,
|
||||
"sponsors": data.Sponsors,
|
||||
"sponsors_panel_title": data.SponsorsPanelTitle,
|
||||
"sponsors_enabled": data.SponsorsEnabled,
|
||||
"sponsors_enabled": data.SponsorsEnabled,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ type updateSettingsRequest struct {
|
||||
BrandMark *string `json:"brand_mark"`
|
||||
BrandLogoSize *string `json:"brand_logo_size"`
|
||||
BrandLogoFit *string `json:"brand_logo_fit"`
|
||||
BrandSloganVisible *bool `json:"brand_slogan_visible"`
|
||||
FooterLinks *[]service.FooterLink `json:"footer_links"`
|
||||
|
||||
PointsCheckinBase *int `json:"points_checkin_base"`
|
||||
@@ -120,6 +121,7 @@ func settingsPayload(saved service.PublicSiteSettings) gin.H {
|
||||
"brand_mark": saved.BrandMark,
|
||||
"brand_logo_size": saved.BrandLogoSize,
|
||||
"brand_logo_fit": saved.BrandLogoFit,
|
||||
"brand_slogan_visible": saved.BrandSloganVisible,
|
||||
"footer_links": saved.FooterLinks,
|
||||
|
||||
"points_checkin_base": saved.PointsCheckinBase,
|
||||
@@ -160,6 +162,7 @@ func (req *updateSettingsRequest) hasAny() bool {
|
||||
req.SiteWordmark != nil || req.SiteSlogan != nil || req.SiteKeywords != nil ||
|
||||
req.LogoLightURL != nil || req.LogoDarkURL != nil || req.FaviconURL != nil ||
|
||||
req.BrandMark != nil || req.BrandLogoSize != nil || req.BrandLogoFit != nil ||
|
||||
req.BrandSloganVisible != nil ||
|
||||
req.FooterLinks != nil ||
|
||||
req.PointsCheckinBase != nil || req.PointsStreakEveryDays != nil || req.PointsStreakBonus != nil ||
|
||||
req.PointsPostReward != nil || req.PointsPostDailyCap != nil ||
|
||||
@@ -540,6 +543,12 @@ func (h *Handlers) UpdateSettings(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.BrandSloganVisible != nil {
|
||||
if err := h.Setting.SetBrandSloganVisible(*req.BrandSloganVisible); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存站点设置失败"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.FooterLinks != nil {
|
||||
if err := h.Setting.SetFooterLinks(*req.FooterLinks); err != nil {
|
||||
if errors.Is(err, service.ErrInvalidSiteSetting) {
|
||||
|
||||
424
backend/handler/snippet.go
Normal file
@@ -0,0 +1,424 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// snippetError 统一错误映射
|
||||
func snippetError(c *gin.Context, err error) {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrSnippetNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "代码片段不存在"})
|
||||
case errors.Is(err, service.ErrSnippetForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "无权操作该代码片段"})
|
||||
case errors.Is(err, service.ErrSnippetBadInput):
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrCommentNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "评论不存在"})
|
||||
case errors.Is(err, service.ErrCommentForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "无权操作该评论"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器错误"})
|
||||
}
|
||||
}
|
||||
|
||||
// SnippetList 公开片段广场
|
||||
func (h *Handlers) SnippetList(c *gin.Context) {
|
||||
q := c.Query("q")
|
||||
lang := c.Query("lang")
|
||||
sort := c.Query("sort")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "12"))
|
||||
items, total, err := h.SnippetSvc.ListPublic(q, lang, sort, page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取片段列表失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// SnippetLanguages 语言白名单
|
||||
func (h *Handlers) SnippetLanguages(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"languages": service.SnippetLanguages()})
|
||||
}
|
||||
|
||||
// SnippetStats 广场聚合统计
|
||||
func (h *Handlers) SnippetStats(c *gin.Context) {
|
||||
stats, err := h.SnippetSvc.Stats()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取统计失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"stats": stats})
|
||||
}
|
||||
|
||||
// SnippetDetail 公开片段详情
|
||||
func (h *Handlers) SnippetDetail(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
var viewerID uint
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
viewerID = claims.ID
|
||||
}
|
||||
isStaff := h.isStaff(c)
|
||||
detail, err := h.SnippetSvc.GetPublic(uint(id), viewerID, isStaff)
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"snippet": detail})
|
||||
}
|
||||
|
||||
// SnippetMine 我的片段列表
|
||||
func (h *Handlers) SnippetMine(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
q := c.Query("q")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "12"))
|
||||
items, total, err := h.SnippetSvc.ListMine(claims.ID, q, page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取片段列表失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// SnippetCreate 创建片段
|
||||
func (h *Handlers) SnippetCreate(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
var in service.SnippetInput
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
snippet, err := h.SnippetSvc.Create(&in, claims.ID)
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"snippet": snippet})
|
||||
}
|
||||
|
||||
// SnippetUpdate 更新片段
|
||||
func (h *Handlers) SnippetUpdate(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
var in service.SnippetInput
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
snippet, err := h.SnippetSvc.Update(uint(id), &in, claims.ID, h.isStaff(c))
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"snippet": snippet})
|
||||
}
|
||||
|
||||
// SnippetDelete 删除片段(owner 或 staff)
|
||||
func (h *Handlers) SnippetDelete(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.SnippetSvc.Delete(uint(id), claims.ID, h.isStaff(c)); err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// SnippetFork Fork 公开片段
|
||||
func (h *Handlers) SnippetFork(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
snippet, err := h.SnippetSvc.Fork(uint(id), claims.ID)
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"snippet": snippet})
|
||||
}
|
||||
|
||||
// SnippetCopy 记录复制(节流由 service 内部处理)
|
||||
func (h *Handlers) SnippetCopy(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
key := c.ClientIP()
|
||||
if claims := middleware.CurrentUser(c); claims != nil {
|
||||
key = "user:" + strconv.FormatUint(uint64(claims.ID), 10)
|
||||
}
|
||||
if err := h.SnippetSvc.RecordCopy(uint(id), key); err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// SnippetHistory 片段编辑历史
|
||||
func (h *Handlers) SnippetHistory(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
|
||||
items, total, err := h.SnippetSvc.ListHistory(uint(id), page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取历史失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// SnippetForks 公开 fork 列表
|
||||
func (h *Handlers) SnippetForks(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "12"))
|
||||
items, total, err := h.SnippetSvc.ListForks(uint(id), page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取 Fork 列表失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// SnippetComments 片段评论列表
|
||||
func (h *Handlers) SnippetComments(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
items, total, err := h.SnippetSvc.ListComments(uint(id), page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取评论失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// SnippetCommentCreate 创建片段评论
|
||||
func (h *Handlers) SnippetCommentCreate(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
snippetID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Content string `json:"content"`
|
||||
ParentID *uint `json:"parent_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
comment, err := h.SnippetSvc.CreateComment(claims.ID, uint(snippetID), in.Content, in.ParentID)
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"comment": comment})
|
||||
}
|
||||
|
||||
// SnippetCommentUpdate 更新片段评论
|
||||
func (h *Handlers) SnippetCommentUpdate(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
cid, err := strconv.ParseUint(c.Param("cid"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
comment, err := h.SnippetSvc.UpdateComment(uint(cid), claims.ID, in.Content)
|
||||
if err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"comment": comment})
|
||||
}
|
||||
|
||||
// SnippetCommentDelete 删除片段评论
|
||||
func (h *Handlers) SnippetCommentDelete(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
cid, err := strconv.ParseUint(c.Param("cid"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.SnippetSvc.DeleteComment(uint(cid), claims.ID, h.isStaff(c)); err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// SnippetCommentHistory 片段评论编辑历史(登录即可见;分页)
|
||||
func (h *Handlers) SnippetCommentHistory(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
cid, err := strconv.ParseUint(c.Param("cid"), 10, 64)
|
||||
if err != nil || cid == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的评论 ID"})
|
||||
return
|
||||
}
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
|
||||
items, total, err := h.SnippetSvc.ListCommentHistory(h.loadActor(claims.ID), uint(cid), page, size)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrCommentNotFound):
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
case errors.Is(err, service.ErrCommentForbidden):
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取编辑历史失败"})
|
||||
}
|
||||
return
|
||||
}
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if size < 1 || size > 50 {
|
||||
size = 10
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"size": size,
|
||||
})
|
||||
}
|
||||
|
||||
// AdminSnippetList 管理端片段列表
|
||||
func (h *Handlers) AdminSnippetList(c *gin.Context) {
|
||||
q := c.Query("q")
|
||||
visibility := c.Query("visibility")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
||||
items, total, err := h.SnippetSvc.AdminList(q, visibility, page, size)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取片段列表失败"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"items": nonNilSlice(items), "total": total})
|
||||
}
|
||||
|
||||
// AdminSnippetDelete 管理端软删片段
|
||||
func (h *Handlers) AdminSnippetDelete(c *gin.Context) {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
if err := h.SnippetSvc.AdminDelete(uint(id), claims.ID); err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// AdminSnippetSetVisibility 管理端强制修改可见性
|
||||
func (h *Handlers) AdminSnippetSetVisibility(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的片段 ID"})
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Visibility string `json:"visibility"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&in); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
if err := h.SnippetSvc.AdminSetVisibility(uint(id), in.Visibility); err != nil {
|
||||
snippetError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
|
||||
// isStaff 判断当前用户是否为管理角色
|
||||
func (h *Handlers) isStaff(c *gin.Context) bool {
|
||||
claims := middleware.CurrentUser(c)
|
||||
if claims == nil {
|
||||
return false
|
||||
}
|
||||
return model.IsStaff(model.Role(claims.Role))
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/middleware"
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"github.com/freefire/jiang13-bbs/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -102,7 +103,7 @@ func (h *Handlers) UploadImage(c *gin.Context) {
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
att, err := h.Upload.SaveImage(claims.ID, f)
|
||||
att, err := h.Upload.SaveImage(claims.ID, f, c.PostForm("source"))
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
if errors.As(err, &maxErr) {
|
||||
@@ -314,7 +315,9 @@ func (h *Handlers) UploadBrandFromMedia(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"url": url})
|
||||
}
|
||||
|
||||
// UploadLibraryCoverFromMedia 把本人媒体库图片复制一份作书籍封面素材,只返回 URL,不绑定条目
|
||||
// UploadLibraryCoverFromMedia 把本人媒体库图片用作书籍封面素材。
|
||||
// 若该图已是封面类型(source=library_cover),直接复用原记录,不再复制;
|
||||
// 否则复制一份并标记为封面类型(与原图解耦,删除原图不影响封面)。
|
||||
func (h *Handlers) UploadLibraryCoverFromMedia(c *gin.Context) {
|
||||
var req struct {
|
||||
AttachmentID uint `json:"attachment_id"`
|
||||
@@ -328,7 +331,14 @@ func (h *Handlers) UploadLibraryCoverFromMedia(c *gin.Context) {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||
return
|
||||
}
|
||||
att, err := h.Upload.CopyImageFromMedia(claims.ID, req.AttachmentID)
|
||||
|
||||
// 已是封面类型的图直接复用,避免重复复制产生冗余记录
|
||||
if existing, err := h.Upload.FindMediaBySource(claims.ID, req.AttachmentID, model.AttachmentSourceLibraryCover); err == nil {
|
||||
c.JSON(http.StatusOK, gin.H{"url": existing.URL, "attachment": existing})
|
||||
return
|
||||
}
|
||||
|
||||
att, err := h.Upload.CopyImageFromMedia(claims.ID, req.AttachmentID, model.AttachmentSourceLibraryCover)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
@@ -404,6 +414,23 @@ func (h *Handlers) MediaLibraryThumb(c *gin.Context) {
|
||||
c.Data(http.StatusOK, "image/webp", data)
|
||||
}
|
||||
|
||||
// ImageVariant 公开图片变体(GET /api/img?u=<源图URL>&w=<白名单宽度>):
|
||||
// 供全站 srcset 消费,源内容不可变 → immutable 长缓存;失败 404 由前端 onError 兜底
|
||||
func (h *Handlers) ImageVariant(c *gin.Context) {
|
||||
w, err := strconv.Atoi(c.Query("w"))
|
||||
if err != nil || !service.IsVariantWidth(w) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的尺寸"})
|
||||
return
|
||||
}
|
||||
data, m, err := h.Upload.Variant(c.Query("u"), w)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "图片不可用"})
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
c.Data(http.StatusOK, m, data)
|
||||
}
|
||||
|
||||
func brandTooLarge(slot string) string {
|
||||
if slot == service.BrandSlotFavicon {
|
||||
return "Favicon 不能超过 512KB"
|
||||
|
||||
@@ -144,11 +144,11 @@ func (h *Handlers) UserProfile(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"user": userPayload,
|
||||
"stats": gin.H{
|
||||
"post_count": postCount,
|
||||
"comment_count": commentCount,
|
||||
"points": pointsTotal,
|
||||
"streak": streak,
|
||||
"favorite_count": favoriteCount,
|
||||
"post_count": postCount,
|
||||
"comment_count": commentCount,
|
||||
"points": pointsTotal,
|
||||
"streak": streak,
|
||||
"favorite_count": favoriteCount,
|
||||
"following_count": followingCount,
|
||||
},
|
||||
"posts": nonNilSlice(posts),
|
||||
|
||||
@@ -85,7 +85,32 @@ func (m *AuthMiddleware) RequireStaff() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// RequirePerm 功能点鉴权,必须接在 RequireStaff 之后
|
||||
// RequireActor 必须登录并加载实时 Actor(不要求管理角色),
|
||||
// 供账号级渠道权限(非管理角色也可被单独授予)所在路由组使用;
|
||||
// 功能点鉴权由后续 RequirePerm 完成
|
||||
func (m *AuthMiddleware) RequireActor() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
claims, ok := m.parseToken(c)
|
||||
if !ok {
|
||||
if c.GetBool(AccountBannedKey) {
|
||||
bannedJSON(c)
|
||||
return
|
||||
}
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
||||
return
|
||||
}
|
||||
actor, err := m.auth.LoadActor(claims.ID)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "无权限执行该操作"})
|
||||
return
|
||||
}
|
||||
c.Set("user", claims)
|
||||
c.Set(ActorKey, actor)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequirePerm 功能点鉴权,必须接在 RequireStaff / RequireActor 之后
|
||||
func (m *AuthMiddleware) RequirePerm(perm string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
actor := CurrentActor(c)
|
||||
|
||||
19
backend/middleware/upload_cache.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UploadStaticCache 上传文件长缓存:/uploads 下文件名均为上传时随机生成、
|
||||
// 写入后不覆盖(SaveAvatar/SaveImage 等均新建文件),URL 内容恒定,可安全
|
||||
// immutable。PageSpeed「缓存生命周期」修复项。
|
||||
func UploadStaticCache() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/uploads/") {
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -19,26 +19,26 @@ const (
|
||||
|
||||
// Ad 赞助广告(游客可申购,管理员审核后展示于首页侧栏)
|
||||
type Ad struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Kind string `gorm:"size:16;not null;index" json:"kind"` // image | text
|
||||
Status string `gorm:"size:16;not null;index" json:"status"` // pending/active/rejected/expired
|
||||
ContactEmail string `gorm:"size:128;not null" json:"contact_email"`
|
||||
LinkURL string `gorm:"size:512;not null" json:"link_url"`
|
||||
ImageURL string `gorm:"size:512" json:"image_url"` // 图片广告
|
||||
Title string `gorm:"size:64" json:"title"` // 文字广告
|
||||
TextColor string `gorm:"size:16" json:"text_color"`
|
||||
BgColor string `gorm:"size:16" json:"bg_color"`
|
||||
DurationDays int `gorm:"not null" json:"duration_days"`
|
||||
PaymentID string `gorm:"size:64;not null" json:"payment_id"`
|
||||
BuyerNote string `gorm:"size:200" json:"buyer_note"`
|
||||
StartsAt *time.Time `json:"starts_at"`
|
||||
EndsAt *time.Time `json:"ends_at"`
|
||||
RejectReason string `gorm:"size:200" json:"reject_reason"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
SubmitIP string `gorm:"size:45" json:"-"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
ReviewedBy *uint `json:"reviewed_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Kind string `gorm:"size:16;not null;index" json:"kind"` // image | text
|
||||
Status string `gorm:"size:16;not null;index" json:"status"` // pending/active/rejected/expired
|
||||
ContactEmail string `gorm:"size:128;not null" json:"contact_email"`
|
||||
LinkURL string `gorm:"size:512;not null" json:"link_url"`
|
||||
ImageURL string `gorm:"size:512" json:"image_url"` // 图片广告
|
||||
Title string `gorm:"size:64" json:"title"` // 文字广告
|
||||
TextColor string `gorm:"size:16" json:"text_color"`
|
||||
BgColor string `gorm:"size:16" json:"bg_color"`
|
||||
DurationDays int `gorm:"not null" json:"duration_days"`
|
||||
PaymentID string `gorm:"size:64;not null" json:"payment_id"`
|
||||
BuyerNote string `gorm:"size:200" json:"buyer_note"`
|
||||
StartsAt *time.Time `json:"starts_at"`
|
||||
EndsAt *time.Time `json:"ends_at"`
|
||||
RejectReason string `gorm:"size:200" json:"reject_reason"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
SubmitIP string `gorm:"size:45" json:"-"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
ReviewedBy *uint `json:"reviewed_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ func InitDB(dsn string) error {
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(
|
||||
&TemporaryUpload{}, &ModuleConfig{}, &SettingsAudit{}, &ActionCounter{}, &MailTask{}, &EmailChallenge{}, &StoredObject{},
|
||||
&TemporaryUpload{}, &ModuleConfig{}, &SettingsAudit{}, &ActionCounter{}, &MailTask{}, &EmailChallenge{}, &StoredObject{}, &Blob{},
|
||||
&User{}, &Board{}, &Post{}, &PostEditHistory{}, &Comment{}, &CommentEditHistory{}, &RefreshToken{}, &Like{}, &Favorite{}, &Follow{}, &Notification{}, &Checkin{},
|
||||
&Announcement{}, &SitePage{}, &SiteSetting{}, &SiteDailyStats{}, &SiteDailyVisitor{}, &VisitEvent{}, &Attachment{}, &UserBoard{}, &LoginLog{},
|
||||
&ChatRoom{}, &ChatRoomMember{}, &ChatMessage{},
|
||||
@@ -64,6 +64,7 @@ func InitDB(dsn string) error {
|
||||
&Badge{}, &UserBadge{},
|
||||
&PostPollVote{}, &PostLotteryEntry{}, &Ad{}, &SidebarWidget{}, &FriendLink{},
|
||||
&ImportRecord{}, &LibraryDoc{}, &LibraryFile{}, &LibrarySection{},
|
||||
&CodeSnippet{}, &SnippetVersion{}, &SnippetComment{}, &SnippetCommentEditHistory{},
|
||||
); err != nil {
|
||||
return fmt.Errorf("自动迁移失败: %w", err)
|
||||
}
|
||||
@@ -78,6 +79,9 @@ func InitDB(dsn string) error {
|
||||
// 每次启动执行,幂等自愈,保证与 CreditTx 增量口径一致(均排除 bounty_refund)
|
||||
backfillUserTotalPoints(db)
|
||||
|
||||
// 书库:历史条目 creator_id=0 时介绍页无创建者可展示,回填为站长
|
||||
backfillLibraryCreator(db)
|
||||
|
||||
// login_logs.success 早期 default=true 与 GORM 零值省略叠加,
|
||||
// 会把失败登录错存为成功;AutoMigrate 不会改列默认值,这里幂等修正
|
||||
if err := db.Exec(`ALTER TABLE login_logs ALTER COLUMN success SET DEFAULT false`).Error; err != nil {
|
||||
@@ -146,6 +150,7 @@ func dropStaleChatFKConstraints(db *gorm.DB) error {
|
||||
pairs := []struct{ table, constraint string }{
|
||||
{"chat_rooms", "fk_chat_rooms_last_message"},
|
||||
{"notifications", "fk_notifications_room"},
|
||||
{"chat_messages", "fk_chat_messages_sender"},
|
||||
}
|
||||
for _, p := range pairs {
|
||||
db.Exec(fmt.Sprintf(`ALTER TABLE IF EXISTS %s DROP CONSTRAINT IF EXISTS %s`, p.table, p.constraint))
|
||||
@@ -368,6 +373,29 @@ func backfillUserTotalPoints(db *gorm.DB) {
|
||||
}
|
||||
}
|
||||
|
||||
// backfillLibraryCreator 为历史书库条目(creator_id=0,特性上线前创建或早期导入)
|
||||
// 回填站长为创建者,保证介绍页「创建者」可展示。幂等:仅影响 creator_id=0 的行;
|
||||
// 站长不存在(空库)时跳过,等下次启动自愈。
|
||||
func backfillLibraryCreator(db *gorm.DB) {
|
||||
var owner User
|
||||
err := db.Select("id").Where("role = ?", RoleOwner).Order("id ASC").First(&owner).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("[model] 回填书库创建者前置查询失败: %v", err)
|
||||
return
|
||||
}
|
||||
res := db.Exec(`UPDATE library_docs SET creator_id = ? WHERE creator_id = 0`, owner.ID)
|
||||
if res.Error != nil {
|
||||
log.Printf("[model] 回填书库创建者失败: %v", res.Error)
|
||||
return
|
||||
}
|
||||
if res.RowsAffected > 0 {
|
||||
log.Printf("[model] 已回填书库条目创建者为站长 %d 行", res.RowsAffected)
|
||||
}
|
||||
}
|
||||
|
||||
// backfillBoardDefaults 为升级前已存在的板块补齐新字段默认值。
|
||||
// 以 post_policy 为空作为「迁移前旧行」的判定标志:仅对这些行一次性回填
|
||||
// post_policy=all、visible=true;后续已被显式设置过的行(含站长隐藏的板块)不会被覆盖。
|
||||
|
||||
@@ -122,6 +122,7 @@ type User struct {
|
||||
Role Role `gorm:"size:16;default:user" json:"role"`
|
||||
Banned bool `gorm:"default:false" json:"banned"`
|
||||
CanManageMessages bool `gorm:"not null;default:false" json:"can_manage_messages"` // 站点消息管理(仅站长可授;站长/超管固有全站监管)
|
||||
PermOverrides string `gorm:"size:256;default:''" json:"-"` // 账号级渠道权限覆盖 JSON;仅后台权限服务读取,序列化跳过
|
||||
Points int `gorm:"not null;default:0" json:"points"` // 可用积分余额
|
||||
TotalPoints int `gorm:"not null;default:0" json:"total_points"` // 累计获得积分(经验值,定级依据;消费不减)
|
||||
Level int `gorm:"-" json:"level"` // 用户等级(AfterFind 由 TotalPoints 计算,纯展示不入库)
|
||||
@@ -323,9 +324,9 @@ const (
|
||||
PointReasonBountyEscrow = "bounty_escrow"
|
||||
PointReasonBountyRefund = "bounty_refund"
|
||||
PointReasonBountyAward = "bounty_award"
|
||||
PointReasonPostReward = "post_reward" // 发帖奖励(可配置,0=关闭)
|
||||
PointReasonReplyReward = "reply_reward" // 回复奖励(可配置,0=关闭)
|
||||
PointReasonStreakBonus = "streak_bonus" // 连续签到里程碑加成
|
||||
PointReasonPostReward = "post_reward" // 发帖奖励(可配置,0=关闭)
|
||||
PointReasonReplyReward = "reply_reward" // 回复奖励(可配置,0=关闭)
|
||||
PointReasonStreakBonus = "streak_bonus" // 连续签到里程碑加成
|
||||
PointReasonRecommend = "recommend_reward" // 帖子被推荐奖励(可配置,0=关闭,每帖仅一次)
|
||||
PointReasonAdminAdjust = "admin_adjust" // 管理员手动调整(加分计累计可升级;扣分仅扣余额)
|
||||
PointReasonNecroReply = "necro_reply" // 旧帖回复扣分(可配置,0=关闭)
|
||||
@@ -361,12 +362,13 @@ type PostContentUnlock struct {
|
||||
|
||||
// PostAttachment 帖子文件附件(不走公开静态目录,经 API 鉴权下载)
|
||||
type PostAttachment struct {
|
||||
ObjectID string `gorm:"size:64;index" json:"-"`
|
||||
ObjectID string `gorm:"size:96;index" json:"-"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
PostID uint `gorm:"index;not null;default:0" json:"post_id"` // 0=草稿未绑定
|
||||
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||
Name string `gorm:"size:256;not null" json:"name"` // 原始文件名
|
||||
StoredName string `gorm:"size:64;not null" json:"-"` // 磁盘文件名
|
||||
Name string `gorm:"size:256;not null" json:"name"` // 原始文件名
|
||||
StoredName string `gorm:"size:64;not null" json:"-"` // 磁盘文件名(blob 去重后即内容 hash)
|
||||
BlobHash string `gorm:"size:64;not null;default:'';index" json:"-"` // 内容寻址 hash;空=历史文件,不走引用计数
|
||||
MIME string `gorm:"size:128;not null;default:application/octet-stream" json:"mime"`
|
||||
Size int `gorm:"not null;default:0" json:"size"`
|
||||
PricePoints int `gorm:"not null;default:0" json:"price_points"` // 0=免费
|
||||
@@ -486,7 +488,7 @@ type Notification struct {
|
||||
IsRead bool `gorm:"default:false;index" json:"is_read"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
||||
Actor User `gorm:"foreignKey:ActorID" json:"actor,omitempty"`
|
||||
// PostID 允许为 0(mention/badge 等无关联帖子),禁建 FK 约束,否则 post_id=0 插入违反外键
|
||||
Post Post `gorm:"foreignKey:PostID;constraint:-" json:"post,omitempty"`
|
||||
Room *ChatRoom `gorm:"foreignKey:RoomID;constraint:-" json:"room,omitempty"`
|
||||
@@ -524,19 +526,25 @@ type SitePage struct {
|
||||
|
||||
// LibraryDoc 书库条目(书籍/文档/纯 HTML 页展示;文件独立目录存储,仅经 API 消费)
|
||||
type LibraryDoc struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Slug string `gorm:"size:64;uniqueIndex;not null" json:"slug"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Description string `gorm:"type:text" json:"description"` // markdown 介绍,可空
|
||||
CoverURL string `gorm:"size:512" json:"cover_url"` // 可选图片封面(/uploads/images)
|
||||
Published bool `gorm:"not null;index" json:"published"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Slug string `gorm:"size:64;uniqueIndex;not null" json:"slug"`
|
||||
Title string `gorm:"size:200;not null" json:"title"`
|
||||
Description string `gorm:"type:text" json:"description"` // markdown 介绍,可空
|
||||
CoverURL string `gorm:"size:512" json:"cover_url"` // 可选图片封面(/uploads/images)
|
||||
CoverWidth int `gorm:"not null;default:0" json:"cover_width"` // 封面自然宽(0=未知,前端回退探测)
|
||||
CoverHeight int `gorm:"not null;default:0" json:"cover_height"` // 封面自然高(0=未知,前端回退探测)
|
||||
Published bool `gorm:"not null;index" json:"published"`
|
||||
SortOrder int `gorm:"not null;default:0" json:"sort_order"`
|
||||
// EntriesAuto 全章节条目卡模式:开启后章节内容免写 [entries] 壳,
|
||||
// 「## 标题 + @tags/@summary/字段::值/@source 指令行」自动识别为条目卡(个别章节用 [entries:off] 例外)
|
||||
EntriesAuto bool `gorm:"not null;default:false" json:"entries_auto"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
// Author 书籍作者(自由文本,可填多位,如「鲁迅 译 / 某某注」),仅展示用
|
||||
Author string `gorm:"size:100;not null;default:''" json:"author"`
|
||||
// CreatorID 条目创建者(站点用户;0=历史数据或导入时无对应用户),创建后不变
|
||||
CreatorID uint `gorm:"index;not null;default:0" json:"creator_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// LibraryFile 书库文件(html/pdf/epub 等;存 data/library,不进公开静态目录)
|
||||
@@ -568,6 +576,75 @@ type LibrarySection struct {
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// CodeSnippet 代码片段:用户所有,公开进广场,私有仅自己可见
|
||||
type CodeSnippet struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Title string `gorm:"size:120;not null" json:"title"`
|
||||
Description string `gorm:"type:text" json:"description"`
|
||||
Language string `gorm:"size:32;not null;index" json:"language"`
|
||||
Code string `gorm:"type:text;not null" json:"code"`
|
||||
Visibility string `gorm:"size:16;not null;default:private;index" json:"visibility"` // public/private
|
||||
UserID uint `gorm:"index;not null" json:"user_id"`
|
||||
ForkedFromID *uint `gorm:"index" json:"forked_from_id"`
|
||||
CopyCount int `gorm:"not null;default:0" json:"copy_count"`
|
||||
ViewCount int `gorm:"not null;default:0" json:"view_count"`
|
||||
CommentCount int `gorm:"not null;default:0" json:"comment_count"`
|
||||
ForkCount int `gorm:"not null;default:0" json:"fork_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// SnippetVersion 编辑前旧值快照(同 PostEditHistory 思路)
|
||||
type SnippetVersion struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
SnippetID uint `gorm:"index;not null" json:"snippet_id"`
|
||||
EditorID uint `gorm:"index;not null" json:"editor_id"`
|
||||
OldTitle string `gorm:"size:120;not null;default:''" json:"old_title"`
|
||||
OldLanguage string `gorm:"size:32;not null;default:''" json:"old_language"`
|
||||
OldDescription string `gorm:"type:text" json:"old_description"`
|
||||
OldCode string `gorm:"type:text;not null" json:"old_code"`
|
||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||
}
|
||||
|
||||
// SnippetComment 片段评论(楼层树:ParentID 空=主评,非空=回复;RootID=所属主楼)
|
||||
type SnippetComment struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
SnippetID uint `gorm:"index;not null" json:"snippet_id"`
|
||||
UserID uint `gorm:"index;not null" json:"user_id,omitempty"`
|
||||
ParentID *uint `gorm:"index" json:"parent_id"`
|
||||
RootID *uint `gorm:"index" json:"root_id"`
|
||||
Depth int `gorm:"not null;default:0" json:"depth"`
|
||||
Content string `gorm:"type:text;not null" json:"content"`
|
||||
DeleteType string `gorm:"size:32;default:''" json:"delete_type,omitempty"`
|
||||
DeletedBy uint `gorm:"not null;default:0" json:"deleted_by,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// SnippetCommentEditHistory 片段评论修订快照(每次编辑前的旧正文;登录用户可见)
|
||||
type SnippetCommentEditHistory struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
CommentID uint `gorm:"index;not null" json:"comment_id"`
|
||||
EditorID uint `gorm:"index;not null" json:"editor_id"`
|
||||
OldContent string `gorm:"type:text;not null" json:"old_content"`
|
||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
SnippetVisibilityPublic = "public"
|
||||
SnippetVisibilityPrivate = "private"
|
||||
)
|
||||
|
||||
// NormalizeSnippetVisibility 归一化可见性:空或未知值一律回落 private
|
||||
func NormalizeSnippetVisibility(v string) string {
|
||||
if v == SnippetVisibilityPublic {
|
||||
return SnippetVisibilityPublic
|
||||
}
|
||||
return SnippetVisibilityPrivate
|
||||
}
|
||||
|
||||
// SiteSetting 站点级键值设置(如历史在线峰值 peak_online)
|
||||
type SiteSetting struct {
|
||||
Key string `gorm:"primaryKey;size:64" json:"key"`
|
||||
@@ -590,20 +667,20 @@ type SidebarWidget struct {
|
||||
|
||||
// FriendLink 友情链接;申请审批制,status=pending 经管理员 approve 后前台可见
|
||||
type FriendLink struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Name string `gorm:"size:64;not null" json:"name"`
|
||||
URL string `gorm:"size:512;not null" json:"url"`
|
||||
Description string `gorm:"size:255" json:"description"`
|
||||
LogoURL string `gorm:"size:512" json:"logo_url"`
|
||||
Category string `gorm:"size:32;index" json:"category"`
|
||||
ReciprocalURL string `gorm:"size:512" json:"reciprocal_url"` // 申请人填写的回链地址,供站长核对
|
||||
SortOrder int `gorm:"not null;default:0;index" json:"sort_order"`
|
||||
Status string `gorm:"size:16;not null;default:'pending';index" json:"status"` // pending|approved|rejected
|
||||
ApplicantUserID *uint `gorm:"index" json:"applicant_user_id,omitempty"` // 后台直接新建时为 nil
|
||||
RejectReason string `gorm:"size:255" json:"reject_reason,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
Name string `gorm:"size:64;not null" json:"name"`
|
||||
URL string `gorm:"size:512;not null" json:"url"`
|
||||
Description string `gorm:"size:255" json:"description"`
|
||||
LogoURL string `gorm:"size:512" json:"logo_url"`
|
||||
Category string `gorm:"size:32;index" json:"category"`
|
||||
ReciprocalURL string `gorm:"size:512" json:"reciprocal_url"` // 申请人填写的回链地址,供站长核对
|
||||
SortOrder int `gorm:"not null;default:0;index" json:"sort_order"`
|
||||
Status string `gorm:"size:16;not null;default:'pending';index" json:"status"` // pending|approved|rejected
|
||||
ApplicantUserID *uint `gorm:"index" json:"applicant_user_id,omitempty"` // 后台直接新建时为 nil
|
||||
RejectReason string `gorm:"size:255" json:"reject_reason,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
}
|
||||
|
||||
// SiteDailyStats 站点日维度访问量(轻量 PV/UV)
|
||||
@@ -652,12 +729,21 @@ const (
|
||||
AttachmentKindImage = "image" // 通用图片(帖子插图等,媒体库统一管理)
|
||||
)
|
||||
|
||||
// Attachment 用户上传的附件(当前仅头像,全部为 WebP)
|
||||
// 附件来源(Source):媒体库分组依据,决定"从图库选图"时是否可直接复用
|
||||
const (
|
||||
AttachmentSourcePost = "post" // 帖子/文章编辑器插图(默认)
|
||||
AttachmentSourceLibraryCover = "library_cover" // 书库封面(选用时已复制过,再次选可直接引用)
|
||||
AttachmentSourceLibraryContent = "library_content" // 书库正文内容插图
|
||||
)
|
||||
|
||||
// Attachment 用户上传的附件(头像与帖子插图等公开图片)
|
||||
type Attachment struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UserID uint `gorm:"index:idx_attachment_user_kind,priority:1;not null" json:"user_id"`
|
||||
Kind string `gorm:"size:16;index:idx_attachment_user_kind,priority:2;not null" json:"kind"`
|
||||
Source string `gorm:"size:24;not null;default:'post'" json:"source"`
|
||||
URL string `gorm:"size:512;not null" json:"url"`
|
||||
BlobHash string `gorm:"size:64;not null;default:'';index" json:"-"` // 内容寻址 hash;空=历史文件,不走引用计数
|
||||
MIME string `gorm:"size:32;not null;default:image/webp" json:"mime"`
|
||||
Size int `gorm:"not null;default:0" json:"size"` // 裁剪后文件字节数(大小限制以此为准)
|
||||
Width int `gorm:"not null;default:0" json:"width"`
|
||||
@@ -665,6 +751,20 @@ type Attachment struct {
|
||||
CreatedAt time.Time `gorm:"index" json:"created_at"`
|
||||
}
|
||||
|
||||
// Blob 内容寻址物理文件:对【最终存储字节】算 SHA-256,同内容多次上传共享一份底层存储,
|
||||
// 业务行(Attachment/PostAttachment 及未来的聊天文件消息)只引用 hash,按引用计数回收。
|
||||
// 公开(帖子插图/头像)与私有(付费附件、未来私聊文件)是两个互不可见的命名空间:
|
||||
// 同字节也各自存一份,避免私有文件借公开链接(/api/media/<id>)被越权读取。
|
||||
type Blob struct {
|
||||
Hash string `gorm:"primaryKey;size:64" json:"-"` // 最终存储字节的 SHA-256 hex(图片为转码后的字节)
|
||||
Public bool `gorm:"primaryKey" json:"-"`
|
||||
RefCount int64 `gorm:"not null;default:0" json:"-"`
|
||||
Size int `gorm:"not null;default:0" json:"-"`
|
||||
MIME string `gorm:"size:128;not null;default:''" json:"-"`
|
||||
ObjectID string `gorm:"size:96;not null;default:''" json:"-"` // S3 后端的 StoredObject ID;本地后端为空
|
||||
CreatedAt time.Time `json:"-"`
|
||||
}
|
||||
|
||||
// UserBoard 板块管理员的板块授权(多对多;仅 role=board_admin 的行生效)
|
||||
type UserBoard struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
@@ -736,6 +836,7 @@ type ChatRoomMember struct {
|
||||
Role string `gorm:"size:16;not null;default:member" json:"role"`
|
||||
LastReadMessageID uint `gorm:"not null;default:0" json:"last_read_message_id"`
|
||||
Muted bool `gorm:"not null;default:false" json:"muted"` // 被群主禁言
|
||||
MutedUntil *time.Time `json:"muted_until,omitempty"` // 禁言截止时间;nil 表示永久
|
||||
PinnedAt *time.Time `json:"pinned_at,omitempty"` // 该用户个人置顶时间;大厅强制置顶不依赖此字段
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
@@ -747,17 +848,18 @@ type ChatRoomMember struct {
|
||||
type ChatMessage struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
RoomID uint `gorm:"index:idx_chat_room_created,priority:1;not null" json:"room_id"`
|
||||
SenderID uint `gorm:"index;not null" json:"sender_id"`
|
||||
SenderID uint `gorm:"index" json:"sender_id"` // 0 表示系统消息(is_system=true)
|
||||
Content string `gorm:"type:varchar(2000);not null" json:"content"`
|
||||
ReplyToID uint `gorm:"not null;default:0;index" json:"reply_to_id"` // 引用的消息 ID,0 表示无引用
|
||||
ReplySnap string `gorm:"size:512;not null;default:''" json:"reply_snap"` // 引用快照「昵称: 摘要」,原文撤回后仍可展示
|
||||
MentionIDs string `gorm:"size:512;not null;default:''" json:"-"` // 被@用户 ID 逗号分隔(落通知用)
|
||||
RecalledAt *time.Time `json:"recalled_at,omitempty"`
|
||||
RecalledBy uint `gorm:"not null;default:0" json:"recalled_by"`
|
||||
IsSystem bool `gorm:"not null;default:false" json:"is_system"` // 系统提示(如禁言通知),sender_id=0
|
||||
CreatedAt time.Time `gorm:"index:idx_chat_room_created,priority:2" json:"created_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||
|
||||
Sender User `gorm:"foreignKey:SenderID" json:"sender,omitempty"`
|
||||
Sender User `gorm:"foreignKey:SenderID;constraint:-" json:"sender,omitempty"` // constraint:- 禁用 FK,支持 sender_id=0 的系统消息
|
||||
// RecalledBy=0 时不建 FK;Preload 仅用于已撤回消息展示撤回者昵称
|
||||
Recaller *User `gorm:"foreignKey:RecalledBy;constraint:-" json:"recaller,omitempty"`
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ type EmailChallenge struct {
|
||||
|
||||
// Every remote object pins the immutable configuration revision that wrote it.
|
||||
type StoredObject struct {
|
||||
ID string `gorm:"primaryKey;size:64" json:"id"`
|
||||
ID string `gorm:"primaryKey;size:96" json:"id"`
|
||||
ConfigName string `gorm:"size:64;index" json:"-"`
|
||||
Key string `gorm:"size:512" json:"-"`
|
||||
MIME string `gorm:"size:128" json:"-"`
|
||||
|
||||
@@ -18,18 +18,19 @@ import (
|
||||
|
||||
// 事件类型:前后端共享的单层 JSON 协议契约,禁止手拼 JSON / 双重编码
|
||||
const (
|
||||
EventHello = "hello" // 建连欢迎帧(含在线用户快照)
|
||||
EventPong = "pong" // 应用层心跳应答
|
||||
EventSettingsChanged = "settings:changed" // 站点设置(主题色)变更,全员广播
|
||||
EventPresenceUpdate = "presence:update" // 用户上/下线,仅 staff 房间
|
||||
EventChatMessage = "chat:message" // 群聊新消息,推 chat:{roomID}
|
||||
EventChatMembership = "chat:membership" // 群成员关系变更(被踢/群解散/被邀请),推 user:{id}
|
||||
EventNotificationNew = "notification:new" // 新站内通知(如群聊 @),推 user:{id}
|
||||
EventFeedChanged = "feed:changed" // 帖子流有公开新内容(三期),全员广播
|
||||
EventChatRecalled = "chat:message_recalled" // 消息撤回,推 chat:{roomID}
|
||||
EventChatUnread = "chat:unread" // 未读增量,推 user:{id}(未订阅房间也能实时角标)
|
||||
EventModerationChanged = "moderation:changed" // 待审队列变化,推 staff 房间(客户端各自 HTTP 校准角标)
|
||||
EventSessionReplaced = "session:replaced" // 登录态被顶/被剔除,推 user:{id}(旧设备即时感知并提示重新登录)
|
||||
EventHello = "hello" // 建连欢迎帧(含在线用户快照)
|
||||
EventPong = "pong" // 应用层心跳应答
|
||||
EventSettingsChanged = "settings:changed" // 站点设置(主题色)变更,全员广播
|
||||
EventPresenceUpdate = "presence:update" // 用户上/下线,仅 staff 房间
|
||||
EventChatMessage = "chat:message" // 群聊新消息,推 chat:{roomID}
|
||||
EventChatMembership = "chat:membership" // 群成员关系变更(被踢/群解散/被邀请),推 user:{id}
|
||||
EventNotificationNew = "notification:new" // 新站内通知(如群聊 @),推 user:{id}
|
||||
EventFeedChanged = "feed:changed" // 帖子流有公开新内容(三期),全员广播
|
||||
EventChatRecalled = "chat:message_recalled" // 消息撤回,推 chat:{roomID}
|
||||
EventChatMemberMuted = "chat:member_muted" // 成员被禁言/解禁,推 chat:{roomID}
|
||||
EventChatUnread = "chat:unread" // 未读增量,推 user:{id}(未订阅房间也能实时角标)
|
||||
EventModerationChanged = "moderation:changed" // 待审队列变化,推 staff 房间(客户端各自 HTTP 校准角标)
|
||||
EventSessionReplaced = "session:replaced" // 登录态被顶/被剔除,推 user:{id}(旧设备即时感知并提示重新登录)
|
||||
)
|
||||
|
||||
// RoomStaff 管理团队房间(板块管理员及以上)
|
||||
|
||||
@@ -101,7 +101,10 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
postFileSvc.WithOperations(ops)
|
||||
pointsSvc := service.NewPointsService(model.DB)
|
||||
leaderboardSvc := service.NewLeaderboardService(model.DB)
|
||||
librarySvc := service.NewLibraryService(model.DB, cfg.DataDir).WithSetting(settingSvc)
|
||||
librarySvc := service.NewLibraryService(model.DB, cfg.DataDir).
|
||||
WithSetting(settingSvc).
|
||||
WithUploadsDir(filepath.Join(cfg.DataDir, "uploads"))
|
||||
snippetSvc := service.NewSnippetService(model.DB)
|
||||
adminUserSvc := service.NewAdminUserService(model.DB)
|
||||
legacyImportSvc := service.NewLegacyImportService(model.DB, filepath.Join(cfg.DataDir, "uploads"))
|
||||
moderationSvc := service.NewModerationService(model.DB, notifSvc)
|
||||
@@ -163,6 +166,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
Badge: badgeSvc,
|
||||
LeaderboardSvc: leaderboardSvc,
|
||||
LibrarySvc: librarySvc,
|
||||
SnippetSvc: snippetSvc,
|
||||
}
|
||||
// 通知落库后统一推 WS 红点(点赞/评论/审核/@ 等共用)
|
||||
notifSvc.OnNotifyNew = func(userID uint) {
|
||||
@@ -183,6 +187,9 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
// 挂在 OptionalAuth 之后可顺带拿到登录用户
|
||||
r.Use(middleware.VisitCapture(visitSvc))
|
||||
|
||||
// 上传文件长缓存(必须先于 r.Static 注册;文件名随机不覆盖,可 immutable)
|
||||
r.Use(middleware.UploadStaticCache())
|
||||
|
||||
// 上传文件静态服务(data/uploads → /uploads)
|
||||
r.Static("/uploads", filepath.Join(cfg.DataDir, "uploads"))
|
||||
|
||||
@@ -209,7 +216,6 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
pubAPI.POST("/posts/:id/unlock-password", middleware.CSRFMiddleware(), middleware.RateLimitMiddleware(limiter, service.RateHidePassword), h.UnlockPostPassword)
|
||||
pubAPI.GET("/posts/:id/attachments/:aid/download", h.DownloadPostAttachment)
|
||||
pubAPI.GET("/posts/:id/comments", h.PostComments)
|
||||
pubAPI.GET("/posts/:id/comments/:cid", h.CommentLocation)
|
||||
pubAPI.GET("/users/:id", h.UserProfile)
|
||||
pubAPI.GET("/users/:id/comments", h.UserComments)
|
||||
pubAPI.GET("/users/:id/favorites", h.UserFavorites)
|
||||
@@ -225,7 +231,16 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
pubAPI.GET("/library", h.LibraryList)
|
||||
pubAPI.GET("/library/:slug", h.LibraryDetail)
|
||||
pubAPI.GET("/library/files/:fid/download", h.LibraryFileDownload)
|
||||
// 代码片段(公开广场/详情/评论/Fork 列表)
|
||||
pubAPI.GET("/snippets", h.SnippetList)
|
||||
pubAPI.GET("/snippets/languages", h.SnippetLanguages)
|
||||
pubAPI.GET("/snippets/stats", h.SnippetStats)
|
||||
pubAPI.GET("/snippets/:id", h.SnippetDetail)
|
||||
pubAPI.GET("/snippets/:id/comments", h.SnippetComments)
|
||||
pubAPI.GET("/snippets/:id/forks", h.SnippetForks)
|
||||
pubAPI.GET("/site-state", h.SiteState)
|
||||
// 自适应图片变体(?u=<源图URL>&w=<白名单宽度>,公开只读、immutable 缓存)
|
||||
pubAPI.GET("/img", h.ImageVariant)
|
||||
pubAPI.GET("/media/:object", h.PublicObject)
|
||||
pubAPI.POST("/auth/code", middleware.CSRFMiddleware(), h.SendEmailCode)
|
||||
pubAPI.POST("/auth/reset-password", middleware.CSRFMiddleware(), h.ResetPassword)
|
||||
@@ -302,6 +317,19 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
// 时间线:从 Git releases 页导入更新日志
|
||||
api.POST("/timeline/from-releases", middleware.StaffExempt(middleware.RateLimitUserMiddleware(limiter, service.RateTimelineGit)), h.TimelineFromReleases)
|
||||
|
||||
// 代码片段(登录区)
|
||||
api.POST("/snippets", middleware.StaffExempt(middleware.RateLimitMiddleware(limiter, service.RateSnippet)), h.SnippetCreate)
|
||||
api.GET("/snippets/mine", h.SnippetMine)
|
||||
api.PUT("/snippets/:id", h.SnippetUpdate)
|
||||
api.DELETE("/snippets/:id", h.SnippetDelete)
|
||||
api.POST("/snippets/:id/fork", middleware.StaffExempt(middleware.RateLimitMiddleware(limiter, service.RateSnippet)), h.SnippetFork)
|
||||
api.POST("/snippets/:id/copy", h.SnippetCopy)
|
||||
api.GET("/snippets/:id/history", h.SnippetHistory)
|
||||
api.POST("/snippets/:id/comments", middleware.StaffExempt(middleware.RateLimitMiddleware(limiter, service.RateComment)), h.SnippetCommentCreate)
|
||||
api.PUT("/snippets/:id/comments/:cid", middleware.StaffExempt(middleware.RateLimitMiddleware(limiter, service.RateComment)), h.SnippetCommentUpdate)
|
||||
api.DELETE("/snippets/:id/comments/:cid", h.SnippetCommentDelete)
|
||||
api.GET("/snippets/:id/comments/:cid/history", h.SnippetCommentHistory)
|
||||
|
||||
// 群聊(二期):建群/成员/消息/未读;全站关闭消息时前台一律 403
|
||||
chatAPI := api.Group("/chat", h.RequireMessagesOpen)
|
||||
{
|
||||
@@ -376,23 +404,34 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
// 群聊监管:移出后挂到 RequireAuth 组,允许「仅群管/消息 flag」用户访问
|
||||
// (见下方 msgAPI)
|
||||
|
||||
// 站点公告文章管理(管理员及以上)
|
||||
announceAPI := staffAPI.Group("", authMW.RequirePerm(service.PermAnnouncements))
|
||||
// 渠道内容管理(公告/单页/书库/广告):RequireActor 允许任意登录账号进入,
|
||||
// 由 RequirePerm 按渠道权限码放行——角色默认管理员及以上,
|
||||
// 超管/站长亦可将单个渠道授予板块管理员或普通用户(账号级授权)
|
||||
permAPI := r.Group("/api/admin", authMW.RequireActor(), middleware.CSRFMiddleware())
|
||||
|
||||
// 站点公告文章管理(PermAnnouncements)
|
||||
announceAPI := permAPI.Group("", authMW.RequirePerm(service.PermAnnouncements))
|
||||
announceAPI.GET("/announcements", h.AdminListAnnouncements)
|
||||
announceAPI.POST("/announcements", h.AdminCreateAnnouncement)
|
||||
announceAPI.PUT("/announcements/:id", h.AdminUpdateAnnouncement)
|
||||
announceAPI.POST("/announcements/:id/pin", h.AdminToggleAnnouncementPin)
|
||||
announceAPI.DELETE("/announcements/:id", h.AdminDeleteAnnouncement)
|
||||
announceAPI.GET("/pages", h.AdminListSitePages)
|
||||
announceAPI.POST("/pages", h.AdminCreateSitePage)
|
||||
announceAPI.PUT("/pages/:id", h.AdminUpdateSitePage)
|
||||
announceAPI.DELETE("/pages/:id", h.AdminDeleteSitePage)
|
||||
announceAPI.DELETE("/pages/:id/purge", h.AdminPurgeSitePage)
|
||||
|
||||
// 书库管理(管理员及以上,同公告/单页权限)
|
||||
libraryAPI := staffAPI.Group("/library", authMW.RequirePerm(service.PermAnnouncements))
|
||||
// 站点单页管理(PermPages)
|
||||
pagesAPI := permAPI.Group("", authMW.RequirePerm(service.PermPages))
|
||||
pagesAPI.GET("/pages", h.AdminListSitePages)
|
||||
pagesAPI.POST("/pages", h.AdminCreateSitePage)
|
||||
pagesAPI.PUT("/pages/:id", h.AdminUpdateSitePage)
|
||||
pagesAPI.DELETE("/pages/:id", h.AdminDeleteSitePage)
|
||||
pagesAPI.DELETE("/pages/:id/purge", h.AdminPurgeSitePage)
|
||||
|
||||
// 书库管理(PermLibrary)
|
||||
libraryAPI := permAPI.Group("/library", authMW.RequirePerm(service.PermLibrary))
|
||||
{
|
||||
libraryAPI.GET("/docs", h.AdminListLibraryDocs)
|
||||
libraryAPI.GET("/export", h.AdminExportAllLibrary)
|
||||
libraryAPI.POST("/import", middleware.RateLimitMiddleware(limiter, service.RateUpload), h.AdminImportLibrary)
|
||||
libraryAPI.GET("/docs/:id/export", h.AdminExportLibraryDoc)
|
||||
libraryAPI.POST("/docs", h.AdminCreateLibraryDoc)
|
||||
libraryAPI.PUT("/docs/:id", h.AdminUpdateLibraryDoc)
|
||||
libraryAPI.DELETE("/docs/:id", h.AdminDeleteLibraryDoc)
|
||||
@@ -409,8 +448,8 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
libraryAPI.POST("/cover/from-media", middleware.RateLimitMiddleware(limiter, service.RateUpload), h.UploadLibraryCoverFromMedia)
|
||||
}
|
||||
|
||||
// 广告位管理(管理员及以上)
|
||||
adsAPI := staffAPI.Group("", authMW.RequirePerm(service.PermAnnouncements))
|
||||
// 广告位管理(PermAds)
|
||||
adsAPI := permAPI.Group("", authMW.RequirePerm(service.PermAds))
|
||||
adsAPI.GET("/ads/config", h.AdminGetAdsConfig)
|
||||
adsAPI.PUT("/ads/config", h.AdminSaveAdsConfig)
|
||||
adsAPI.GET("/ads", h.AdminListAds)
|
||||
@@ -477,6 +516,8 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
usersAPI.GET("/users", h.AdminListUsers)
|
||||
usersAPI.PUT("/users/:id/role", h.AdminUpdateUserRole)
|
||||
usersAPI.PUT("/users/:id/messages", h.AdminSetUserMessages)
|
||||
usersAPI.GET("/users/:id/perms", h.AdminGetUserPerms)
|
||||
usersAPI.PUT("/users/:id/perms", h.AdminSetUserPerms)
|
||||
usersAPI.PUT("/users/:id/ban", h.AdminSetUserBan)
|
||||
usersAPI.GET("/users/:id/login-logs", h.AdminUserLoginLogs)
|
||||
// 积分管理:手动调整(加分计累计/扣分仅扣余额)与积分流水分页
|
||||
@@ -489,6 +530,11 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
usersAPI.GET("/users/:id/messages", h.AdminUserAuditMessages)
|
||||
}
|
||||
|
||||
// 代码片段管理(任意 staff)
|
||||
staffAPI.GET("/snippets", h.AdminSnippetList)
|
||||
staffAPI.DELETE("/snippets/:id", h.AdminSnippetDelete)
|
||||
staffAPI.PUT("/snippets/:id/visibility", h.AdminSnippetSetVisibility)
|
||||
|
||||
// 板块管理(仅站长):增删改、排序、版主授权
|
||||
boardsAPI := staffAPI.Group("", authMW.RequirePerm(service.PermBoards))
|
||||
{
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
@@ -10,21 +12,119 @@ import (
|
||||
// 板块管理员的板块范围由 Actor.BoardIDs 在业务层二次校验。
|
||||
const (
|
||||
PermUsers = "users" // 用户与权限管理(超管/站长)
|
||||
PermAnnouncements = "announcements" // 公告管理(管理员及以上)
|
||||
PermAnnouncements = "announcements" // 公告管理(管理员及以上;可账号级授予)
|
||||
PermPages = "pages" // 单页管理(管理员及以上;可账号级授予)
|
||||
PermLibrary = "library" // 书库管理(管理员及以上;可账号级授予)
|
||||
PermAds = "ads" // 广告与赞助管理(管理员及以上;可账号级授予)
|
||||
PermSettings = "settings" // 站点外观设置(超管/站长)
|
||||
PermModeration = "moderation" // 内容审核(任意管理角色,板块范围受限)
|
||||
PermMessages = "messages" // 后台消息管理(站长/超管/站点消息 flag;群管另有业务层放行)
|
||||
PermBoards = "boards" // 板块管理(仅站长)
|
||||
)
|
||||
|
||||
// GrantablePerms 可账号级授予的渠道权限码(授予者需持有 PermUsers)。
|
||||
// 管理员及以上角色对这些渠道为角色自带,账号级授予只对板块管理员/普通用户生效。
|
||||
var GrantablePerms = []string{PermAnnouncements, PermPages, PermLibrary, PermAds}
|
||||
|
||||
// ValidPermOverride 权限码是否可被账号级授予
|
||||
func ValidPermOverride(p string) bool {
|
||||
for _, g := range GrantablePerms {
|
||||
if p == g {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NormalizePermOverrides 白名单过滤 + 去重 + 排序,得到可落库的权限码集
|
||||
func NormalizePermOverrides(perms []string) []string {
|
||||
seen := map[string]bool{}
|
||||
out := make([]string, 0, len(perms))
|
||||
for _, p := range perms {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" || seen[p] || !ValidPermOverride(p) {
|
||||
continue
|
||||
}
|
||||
seen[p] = true
|
||||
out = append(out, p)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// ParsePermOverrides 解析 users.perm_overrides JSON 列(容错:非法内容视为空)
|
||||
func ParsePermOverrides(raw string) []string {
|
||||
if raw == "" {
|
||||
return []string{}
|
||||
}
|
||||
var arr []string
|
||||
if err := json.Unmarshal([]byte(raw), &arr); err != nil {
|
||||
return []string{}
|
||||
}
|
||||
return NormalizePermOverrides(arr)
|
||||
}
|
||||
|
||||
// SerializePermOverrides 序列化为落库 JSON(空集统一 "[]",避免 NULL/空串分歧)
|
||||
func SerializePermOverrides(perms []string) string {
|
||||
norm := NormalizePermOverrides(perms)
|
||||
b, err := json.Marshal(norm)
|
||||
if err != nil {
|
||||
return "[]"
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// roleDefaultPerm 角色对功能点的固有权限(不含账号级授予)
|
||||
func roleDefaultPerm(role model.Role, p string) bool {
|
||||
switch p {
|
||||
case PermBoards:
|
||||
return role == model.RoleOwner
|
||||
case PermUsers, PermSettings:
|
||||
return role == model.RoleSuperAdmin || role == model.RoleOwner
|
||||
case PermAnnouncements, PermPages, PermLibrary, PermAds:
|
||||
return model.RoleLevel(role) >= model.RoleLevel(model.RoleAdmin)
|
||||
case PermModeration:
|
||||
return model.IsStaff(role)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// EffectivePerms 生效权限码列表(角色默认 ∪ 账号授予 + 消息管理),
|
||||
// 供 /me 下发,前端据此渲染后台入口/按钮;最终权限仍以 HasPerm 校验为准。
|
||||
func EffectivePerms(role model.Role, permOverridesRaw string, canManageMessages bool) []string {
|
||||
set := map[string]bool{}
|
||||
all := append([]string{
|
||||
PermUsers, PermAnnouncements, PermPages, PermLibrary, PermAds,
|
||||
PermSettings, PermModeration, PermBoards,
|
||||
}, GrantablePerms...)
|
||||
for _, p := range all {
|
||||
if roleDefaultPerm(role, p) {
|
||||
set[p] = true
|
||||
}
|
||||
}
|
||||
for _, p := range ParsePermOverrides(permOverridesRaw) {
|
||||
set[p] = true
|
||||
}
|
||||
if role == model.RoleOwner || role == model.RoleSuperAdmin || canManageMessages {
|
||||
set[PermMessages] = true
|
||||
}
|
||||
out := make([]string, 0, len(set))
|
||||
for p := range set {
|
||||
out = append(out, p)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// Actor 当前请求操作者的实时权限快照(每次后台请求从 DB 现取,
|
||||
// 不依赖 JWT 内的 role claim,角色/授权变更立即生效)
|
||||
type Actor struct {
|
||||
ID uint
|
||||
Username string
|
||||
Role model.Role
|
||||
BoardIDs []uint // 板块管理员被授权的板块;其他角色为空
|
||||
CanManageMessages bool // 站点级消息管理 flag(站长授予);站长/超管不必依赖此字段
|
||||
BoardIDs []uint // 板块管理员被授权的板块;其他角色为空
|
||||
CanManageMessages bool // 站点级消息管理 flag(站长授予);站长/超管不必依赖此字段
|
||||
ExtraPerms []string // 账号级授予的渠道权限(角色固有之外的增量)
|
||||
}
|
||||
|
||||
// IsStaff 是否管理团队成员
|
||||
@@ -32,23 +132,22 @@ func (a *Actor) IsStaff() bool {
|
||||
return a != nil && model.IsStaff(a.Role)
|
||||
}
|
||||
|
||||
// HasPerm 是否拥有某后台功能点
|
||||
// HasPerm 是否拥有某后台功能点:角色固有权限 ∪ 账号级授予
|
||||
func (a *Actor) HasPerm(p string) bool {
|
||||
if a == nil {
|
||||
return false
|
||||
}
|
||||
switch p {
|
||||
case PermBoards:
|
||||
return a.Role == model.RoleOwner
|
||||
case PermUsers, PermSettings:
|
||||
return a.Role == model.RoleSuperAdmin || a.Role == model.RoleOwner
|
||||
case PermAnnouncements:
|
||||
return model.RoleLevel(a.Role) >= model.RoleLevel(model.RoleAdmin)
|
||||
case PermModeration:
|
||||
return a.IsStaff()
|
||||
case PermMessages:
|
||||
if roleDefaultPerm(a.Role, p) {
|
||||
return true
|
||||
}
|
||||
if p == PermMessages {
|
||||
return a.HasSiteMessagePerm()
|
||||
}
|
||||
for _, e := range a.ExtraPerms {
|
||||
if e == p {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -113,15 +212,16 @@ func (a *Actor) CanAssignRole(target model.Role) bool {
|
||||
return a.HasPerm(PermUsers)
|
||||
}
|
||||
|
||||
// LoadActor 读取用户实时角色与板块授权
|
||||
// LoadActor 读取用户实时角色、板块授权与账号级渠道权限
|
||||
func (s *AuthService) LoadActor(id uint) (*Actor, error) {
|
||||
var u model.User
|
||||
if err := s.db.Select("id", "username", "role", "can_manage_messages").First(&u, id).Error; err != nil {
|
||||
if err := s.db.Select("id", "username", "role", "can_manage_messages", "perm_overrides").First(&u, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
actor := &Actor{
|
||||
ID: u.ID, Username: u.Username, Role: u.Role, BoardIDs: []uint{},
|
||||
CanManageMessages: u.CanManageMessages,
|
||||
ExtraPerms: ParsePermOverrides(u.PermOverrides),
|
||||
}
|
||||
if u.Role == model.RoleBoardAdmin {
|
||||
var ids []uint
|
||||
|
||||
@@ -17,25 +17,25 @@ import (
|
||||
const (
|
||||
SettingKeyAdsConfig = "ads_config"
|
||||
|
||||
AdMaxTitleRunes = 24
|
||||
AdMaxNoteRunes = 100
|
||||
AdMaxImageShow = 5
|
||||
AdMaxTextShow = 6
|
||||
AdMaxActiveShow = AdMaxImageShow + AdMaxTextShow
|
||||
AdDefaultTitle = "自助推广"
|
||||
AdMaxTitleRunes = 24
|
||||
AdMaxNoteRunes = 100
|
||||
AdMaxImageShow = 5
|
||||
AdMaxTextShow = 6
|
||||
AdMaxActiveShow = AdMaxImageShow + AdMaxTextShow
|
||||
AdDefaultTitle = "自助推广"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrAdNotFound = errors.New("广告不存在")
|
||||
ErrAdForbidden = errors.New("无权操作")
|
||||
ErrAdInvalid = errors.New("广告参数无效")
|
||||
ErrAdCaptcha = errors.New("验证码错误或已过期")
|
||||
ErrAdDisabled = errors.New("自助推广暂未开放")
|
||||
ErrAdBadPayment = errors.New("请选择有效的支付方式")
|
||||
ErrAdBadDuration = errors.New("请选择有效的投放时长")
|
||||
hexColorRe = regexp.MustCompile(`^#([0-9a-fA-F]{6})$`)
|
||||
adImageHTTPSRe = regexp.MustCompile(`(?i)^https://[^\s\\]{1,500}$`)
|
||||
adImageUploadRe = regexp.MustCompile(`(?i)^/uploads/(ads|images|brand)/[0-9a-f]{32}\.(png|jpe?g|gif|webp)$`)
|
||||
ErrAdNotFound = errors.New("广告不存在")
|
||||
ErrAdForbidden = errors.New("无权操作")
|
||||
ErrAdInvalid = errors.New("广告参数无效")
|
||||
ErrAdCaptcha = errors.New("验证码错误或已过期")
|
||||
ErrAdDisabled = errors.New("自助推广暂未开放")
|
||||
ErrAdBadPayment = errors.New("请选择有效的支付方式")
|
||||
ErrAdBadDuration = errors.New("请选择有效的投放时长")
|
||||
hexColorRe = regexp.MustCompile(`^#([0-9a-fA-F]{6})$`)
|
||||
adImageHTTPSRe = regexp.MustCompile(`(?i)^https://[^\s\\]{1,500}$`)
|
||||
adImageUploadRe = regexp.MustCompile(`(?i)^/uploads/(ads|images|brand)/[0-9a-f]{32}\.(png|jpe?g|gif|webp)$`)
|
||||
)
|
||||
|
||||
// AdDurationOption 可购时长档位(图片 / 文字广告分别计价)
|
||||
|
||||
@@ -49,11 +49,11 @@ const (
|
||||
|
||||
// AdminContentCounts 当前操作者可见范围内的数量(用于页内 Tab)
|
||||
type AdminContentCounts struct {
|
||||
PostsLive int64 `json:"posts_live"`
|
||||
PostsPending int64 `json:"posts_pending"`
|
||||
PostsRejected int64 `json:"posts_rejected"`
|
||||
PostsDeleted int64 `json:"posts_deleted"`
|
||||
CommentsLive int64 `json:"comments_live"`
|
||||
PostsLive int64 `json:"posts_live"`
|
||||
PostsPending int64 `json:"posts_pending"`
|
||||
PostsRejected int64 `json:"posts_rejected"`
|
||||
PostsDeleted int64 `json:"posts_deleted"`
|
||||
CommentsLive int64 `json:"comments_live"`
|
||||
CommentsPending int64 `json:"comments_pending"`
|
||||
CommentsRejected int64 `json:"comments_rejected"`
|
||||
CommentsDeleted int64 `json:"comments_deleted"`
|
||||
@@ -61,32 +61,34 @@ type AdminContentCounts struct {
|
||||
|
||||
// AdminContentPost 后台帖子列表项
|
||||
type AdminContentPost struct {
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Deleted bool `json:"deleted"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
BoardID uint `json:"board_id"`
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Status string `json:"status"`
|
||||
Deleted bool `json:"deleted"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
BoardID uint `json:"board_id"`
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
// AdminContentComment 后台评论列表项
|
||||
type AdminContentComment struct {
|
||||
ID uint `json:"id"`
|
||||
PostID uint `json:"post_id"`
|
||||
PostTitle string `json:"post_title"`
|
||||
BoardID uint `json:"board_id"`
|
||||
Content string `json:"content"`
|
||||
Status string `json:"status"`
|
||||
Edited bool `json:"edited"` // 相对创建已编辑(同评论侧规则),用于隐藏无修订的历史入口
|
||||
Deleted bool `json:"deleted"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uint `json:"id"`
|
||||
PostID uint `json:"post_id"`
|
||||
PostTitle string `json:"post_title"`
|
||||
BoardID uint `json:"board_id"`
|
||||
Content string `json:"content"`
|
||||
Status string `json:"status"`
|
||||
Edited bool `json:"edited"` // 相对创建已编辑(同评论侧规则),用于隐藏无修订的历史入口
|
||||
Deleted bool `json:"deleted"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Floor uint `json:"floor"` // 所属楼层相对序号
|
||||
IsRoot bool `json:"is_root"` // 主楼/楼中楼,供前台拼 #comment-{floor}[-r{id}]
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
func normalizeAdminStatus(raw string) AdminContentStatus {
|
||||
@@ -270,6 +272,11 @@ func (s *ModerationService) ListAdminComments(actor *Actor, status, keyword stri
|
||||
}
|
||||
|
||||
items := make([]AdminContentComment, 0, len(rows))
|
||||
commentIDs := make([]uint, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
commentIDs = append(commentIDs, r.ID)
|
||||
}
|
||||
anchors := CommentAnchors(s.db, commentIDs)
|
||||
for _, r := range rows {
|
||||
it := AdminContentComment{
|
||||
ID: r.ID,
|
||||
@@ -283,6 +290,10 @@ func (s *ModerationService) ListAdminComments(actor *Actor, status, keyword stri
|
||||
Board: boards[r.BoardID],
|
||||
User: users[r.UserID],
|
||||
}
|
||||
if a, ok := anchors[r.ID]; ok {
|
||||
it.Floor = a.Floor
|
||||
it.IsRoot = a.IsRoot
|
||||
}
|
||||
if r.DeletedAt.Valid {
|
||||
it.Deleted = true
|
||||
t := r.DeletedAt.Time
|
||||
|
||||
@@ -54,6 +54,7 @@ type AdminUserItem struct {
|
||||
BoardIDs []uint `json:"board_ids"`
|
||||
Banned bool `json:"banned"`
|
||||
CanManageMessages bool `json:"can_manage_messages"`
|
||||
PermOverrides []string `json:"perm_overrides"` // 账号级渠道权限(角色固有之外的增量授予)
|
||||
PostCount int64 `json:"post_count"`
|
||||
CommentCount int64 `json:"comment_count"`
|
||||
Points int `json:"points"`
|
||||
@@ -71,7 +72,7 @@ type AdminUserItem struct {
|
||||
// - total / admins / banned:筛选 Tab 角标(不在顶部卡片展示,避免与仪表盘重复)
|
||||
type AdminUserSummary struct {
|
||||
Online int64 `json:"online"`
|
||||
InCooldown int64 `json:"in_cooldown"`
|
||||
InCooldown int64 `json:"in_cooldown"`
|
||||
Active7d int64 `json:"active_7d"`
|
||||
FailedLogins24h int64 `json:"failed_logins_24h"`
|
||||
Total int64 `json:"total"`
|
||||
@@ -237,6 +238,7 @@ func (s *AdminUserService) toItems(users []model.User) []AdminUserItem {
|
||||
BoardIDs: []uint{},
|
||||
Banned: u.Banned,
|
||||
CanManageMessages: u.CanManageMessages,
|
||||
PermOverrides: ParsePermOverrides(u.PermOverrides),
|
||||
Points: u.Points,
|
||||
TotalPoints: u.TotalPoints,
|
||||
Level: u.Level,
|
||||
@@ -407,6 +409,12 @@ func (s *AdminUserService) SetStaff(operator *Actor, targetID uint, role model.R
|
||||
return err
|
||||
}
|
||||
}
|
||||
// 升至管理员及以上后渠道权限变为角色自带,账号级授予清空以免误导
|
||||
if roleChanged && model.RoleLevel(role) >= model.RoleLevel(model.RoleAdmin) && u.PermOverrides != "" && u.PermOverrides != "[]" {
|
||||
if err := tx.Model(&u).Update("perm_overrides", "[]").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
@@ -415,6 +423,53 @@ func (s *AdminUserService) SetStaff(operator *Actor, targetID uint, role model.R
|
||||
return s.getItem(s.db, targetID)
|
||||
}
|
||||
|
||||
// GetPermOverrides 读取目标账号的渠道权限(PermUsers 持有者可读,供授权弹窗回显)
|
||||
func (s *AdminUserService) GetPermOverrides(operator *Actor, targetID uint) ([]string, error) {
|
||||
if operator == nil || !operator.HasPerm(PermUsers) {
|
||||
return nil, ErrCannotAssignRole
|
||||
}
|
||||
var u model.User
|
||||
if err := s.db.Select("id", "perm_overrides").First(&u, targetID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ParsePermOverrides(u.PermOverrides), nil
|
||||
}
|
||||
|
||||
// SetPermOverrides 授予/撤销账号级渠道权限(公告/单页/书库/广告)。
|
||||
// 授予者需持有 PermUsers(超管/站长);目标为管理员及以上时渠道为角色自带,
|
||||
// 授权无意义,强制清空。Actor 每次请求现查 DB,变更即时生效,无需强制下线。
|
||||
func (s *AdminUserService) SetPermOverrides(operator *Actor, targetID uint, perms []string) (*AdminUserItem, error) {
|
||||
if operator == nil || !operator.HasPerm(PermUsers) {
|
||||
return nil, ErrCannotAssignRole
|
||||
}
|
||||
if operator.ID == targetID {
|
||||
return nil, ErrAdminSelfAction
|
||||
}
|
||||
norm := NormalizePermOverrides(perms)
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
var u model.User
|
||||
if err := tx.First(&u, targetID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if u.Role == model.RoleOwner {
|
||||
return ErrProtectedOwner
|
||||
}
|
||||
// 管理员及以上角色自带全部渠道权限,账号级授予保持为空
|
||||
if model.RoleLevel(u.Role) >= model.RoleLevel(model.RoleAdmin) {
|
||||
norm = []string{}
|
||||
}
|
||||
raw := SerializePermOverrides(norm)
|
||||
if u.PermOverrides == raw {
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&u).Update("perm_overrides", raw).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.getItem(s.db, targetID)
|
||||
}
|
||||
|
||||
// SetCanManageMessages 站长授予/撤销站点消息管理权限(不可操作站长账号与自己)
|
||||
func (s *AdminUserService) SetCanManageMessages(operator *Actor, targetID uint, enabled bool) (*AdminUserItem, error) {
|
||||
if operator == nil || operator.Role != model.RoleOwner {
|
||||
@@ -564,12 +619,12 @@ func normalizeAuditPage(page, size int) (int, int) {
|
||||
|
||||
// AdminUserAuditProfile 站长查看用户档案摘要
|
||||
type AdminUserAuditProfile struct {
|
||||
User AdminUserItem `json:"user"`
|
||||
PostsTotal int64 `json:"posts_total"` // 含各状态与软删
|
||||
CommentsTotal int64 `json:"comments_total"` // 含各状态与软删
|
||||
MessagesTotal int64 `json:"messages_total"` // 含撤回与软删
|
||||
PublishedPosts int64 `json:"published_posts"`
|
||||
PublishedComments int64 `json:"published_comments"`
|
||||
User AdminUserItem `json:"user"`
|
||||
PostsTotal int64 `json:"posts_total"` // 含各状态与软删
|
||||
CommentsTotal int64 `json:"comments_total"` // 含各状态与软删
|
||||
MessagesTotal int64 `json:"messages_total"` // 含撤回与软删
|
||||
PublishedPosts int64 `json:"published_posts"`
|
||||
PublishedComments int64 `json:"published_comments"`
|
||||
}
|
||||
|
||||
// AdminAuditPostItem 审计帖子行
|
||||
@@ -594,6 +649,8 @@ type AdminAuditCommentItem struct {
|
||||
Deleted bool `json:"deleted"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
Floor uint `json:"floor"`
|
||||
IsRoot bool `json:"is_root"`
|
||||
}
|
||||
|
||||
// AdminAuditMessageItem 审计聊天消息行
|
||||
@@ -686,6 +743,11 @@ func (s *AdminUserService) ListAuditComments(actor *Actor, userID uint, page, si
|
||||
Offset((page - 1) * size).Limit(size).Find(&comments).Error; err != nil {
|
||||
return nil, 0, page, err
|
||||
}
|
||||
commentIDs := make([]uint, 0, len(comments))
|
||||
for _, c := range comments {
|
||||
commentIDs = append(commentIDs, c.ID)
|
||||
}
|
||||
anchors := CommentAnchors(s.db, commentIDs)
|
||||
items := make([]AdminAuditCommentItem, 0, len(comments))
|
||||
for _, c := range comments {
|
||||
it := AdminAuditCommentItem{
|
||||
@@ -695,6 +757,10 @@ func (s *AdminUserService) ListAuditComments(actor *Actor, userID uint, page, si
|
||||
Status: c.Status,
|
||||
CreatedAt: c.CreatedAt,
|
||||
}
|
||||
if a, ok := anchors[c.ID]; ok {
|
||||
it.Floor = a.Floor
|
||||
it.IsRoot = a.IsRoot
|
||||
}
|
||||
if c.DeletedAt.Valid {
|
||||
it.Deleted = true
|
||||
t := c.DeletedAt.Time
|
||||
|
||||
@@ -107,10 +107,13 @@ var dummyPasswordHash, _ = bcrypt.GenerateFromPassword(
|
||||
[]byte("j13-dummy-password-for-constant-timing"), bcrypt.DefaultCost)
|
||||
|
||||
// Register 用户注册(事务 + 咨询锁,保证空库至多一名 owner)
|
||||
// 邮箱非空时全库唯一(忽略大小写):后期支持邮箱登录,一邮箱只能对应一个账号
|
||||
func (s *AuthService) Register(username, email, password string) (*model.User, error) {
|
||||
if err := NewOperations(s.db, nil).Filter("username", username, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 邮箱统一小写归一化,避免大小写变体重复注册
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
@@ -130,6 +133,16 @@ func (s *AuthService) Register(username, email, password string) (*model.User, e
|
||||
if count > 0 {
|
||||
return errors.New("用户名已被使用")
|
||||
}
|
||||
// 邮箱唯一(忽略大小写,兜底防绕过;入口发码处已拦一次)
|
||||
if email != "" {
|
||||
var emailCount int64
|
||||
if err := tx.Model(&model.User{}).Where("LOWER(email) = ?", email).Count(&emailCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if emailCount > 0 {
|
||||
return errors.New("该邮箱已被注册")
|
||||
}
|
||||
}
|
||||
var n int64
|
||||
if err := tx.Model(&model.User{}).Count(&n).Error; err != nil {
|
||||
return err
|
||||
@@ -681,14 +694,14 @@ func (s *AuthService) UpdateProfile(userID uint, nickname, email, signature stri
|
||||
if nickCount > 0 {
|
||||
return nil, errors.New("该昵称已被使用")
|
||||
}
|
||||
email = strings.TrimSpace(email)
|
||||
email = strings.ToLower(strings.TrimSpace(email))
|
||||
if email != "" {
|
||||
if !strings.Contains(email, "@") || len(email) > 128 {
|
||||
return nil, errors.New("邮箱格式不正确")
|
||||
}
|
||||
// 邮箱唯一性校验(排除自身)
|
||||
// 邮箱唯一性校验(忽略大小写,排除自身),与注册口径一致
|
||||
var count int64
|
||||
s.db.Model(&model.User{}).Where("email = ? AND id <> ?", email, userID).Count(&count)
|
||||
s.db.Model(&model.User{}).Where("LOWER(email) = ? AND id <> ?", email, userID).Count(&count)
|
||||
if count > 0 {
|
||||
return nil, errors.New("该邮箱已被使用")
|
||||
}
|
||||
|
||||
223
backend/service/blob_dedup_test.go
Normal file
@@ -0,0 +1,223 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
webpenc "github.com/gen2brain/webp"
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newBlobTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
&model.Blob{}, &model.Attachment{}, &model.PostAttachment{},
|
||||
&model.User{}, &model.Post{},
|
||||
); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func webpFixtureBytes() []byte {
|
||||
src := image.NewRGBA(image.Rect(0, 0, 20, 10))
|
||||
src.Set(0, 0, color.RGBA{10, 20, 30, 255})
|
||||
var buf bytes.Buffer
|
||||
_ = webpenc.Encode(&buf, src, webpenc.Options{Quality: ImageWebPQuality})
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestSaveImageBlobDedupAndRefcount(t *testing.T) {
|
||||
db := newBlobTestDB(t)
|
||||
dir := t.TempDir()
|
||||
s := NewUploadService(db, dir)
|
||||
if err := s.EnsureDir(); err != nil {
|
||||
t.Fatalf("ensure dir: %v", err)
|
||||
}
|
||||
data := webpFixtureBytes()
|
||||
|
||||
att1, err := s.SaveImage(1, bytes.NewReader(data), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage 1: %v", err)
|
||||
}
|
||||
att2, err := s.SaveImage(2, bytes.NewReader(data), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage 2: %v", err)
|
||||
}
|
||||
if att1.URL != att2.URL || att1.BlobHash == "" || att1.BlobHash != att2.BlobHash {
|
||||
t.Fatalf("identical content should share url/hash: %q vs %q", att1.URL, att2.URL)
|
||||
}
|
||||
|
||||
var blob model.Blob
|
||||
if err := db.First(&blob, "hash = ? AND public = ?", att1.BlobHash, true).Error; err != nil {
|
||||
t.Fatalf("load blob: %v", err)
|
||||
}
|
||||
if blob.RefCount != 2 {
|
||||
t.Fatalf("refcount want 2, got %d", blob.RefCount)
|
||||
}
|
||||
blobPath := filepath.Join(dir, filepath.FromSlash(att1.URL[len("/uploads/"):]))
|
||||
if fi, err := os.Stat(blobPath); err != nil || fi.IsDir() {
|
||||
t.Fatalf("shared physical file missing: %v", err)
|
||||
}
|
||||
|
||||
// 删一个引用:文件保留
|
||||
if err := s.DeleteAttachment(1, att1.ID); err != nil {
|
||||
t.Fatalf("DeleteAttachment 1: %v", err)
|
||||
}
|
||||
db.First(&blob, "hash = ? AND public = ?", att1.BlobHash, true)
|
||||
if blob.RefCount != 1 {
|
||||
t.Fatalf("refcount want 1, got %d", blob.RefCount)
|
||||
}
|
||||
if _, err := os.Stat(blobPath); err != nil {
|
||||
t.Fatalf("blob file should survive while referenced: %v", err)
|
||||
}
|
||||
|
||||
// 最后一个引用删除:文件与 blob 行一起回收
|
||||
if err := s.DeleteAttachment(2, att2.ID); err != nil {
|
||||
t.Fatalf("DeleteAttachment 2: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(blobPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("blob file should be removed after last release, stat err=%v", err)
|
||||
}
|
||||
var n int64
|
||||
db.Model(&model.Blob{}).Where("hash = ? AND public = ?", att1.BlobHash, true).Count(&n)
|
||||
if n != 0 {
|
||||
t.Fatalf("blob row should be gone, count=%d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveImageTranscodedJPEGDedup(t *testing.T) {
|
||||
db := newBlobTestDB(t)
|
||||
dir := t.TempDir()
|
||||
s := NewUploadService(db, dir)
|
||||
if err := s.EnsureDir(); err != nil {
|
||||
t.Fatalf("ensure dir: %v", err)
|
||||
}
|
||||
|
||||
src := image.NewRGBA(image.Rect(0, 0, 48, 36))
|
||||
src.Set(1, 2, color.RGBA{200, 100, 50, 255})
|
||||
var in bytes.Buffer
|
||||
if err := jpeg.Encode(&in, src, nil); err != nil {
|
||||
t.Fatalf("encode jpeg: %v", err)
|
||||
}
|
||||
|
||||
att1, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage 1: %v", err)
|
||||
}
|
||||
att2, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage 2: %v", err)
|
||||
}
|
||||
// hash 必须对转码后的字节计算:同源 JPEG 两次上传应命中同一个 WebP blob
|
||||
if att1.URL != att2.URL || att1.BlobHash != att2.BlobHash {
|
||||
t.Fatalf("transcoded JPEG should dedup: %q(%s) vs %q(%s)", att1.URL, att1.BlobHash, att2.URL, att2.BlobHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveDraftFileBlobDedupAndRefcount(t *testing.T) {
|
||||
db := newBlobTestDB(t)
|
||||
root := t.TempDir()
|
||||
s := NewPostFileService(db, root)
|
||||
if err := s.EnsureDir(); err != nil {
|
||||
t.Fatalf("ensure dir: %v", err)
|
||||
}
|
||||
data := []byte("paid attachment content v1")
|
||||
|
||||
a1, err := s.SaveDraftFile(1, "report.pdf", bytes.NewReader(data), 50)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveDraftFile 1: %v", err)
|
||||
}
|
||||
a2, err := s.SaveDraftFile(2, "another-name.pdf", bytes.NewReader(data), 0)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveDraftFile 2: %v", err)
|
||||
}
|
||||
if a1.BlobHash == "" || a1.BlobHash != a2.BlobHash || a1.StoredName != a2.StoredName {
|
||||
t.Fatalf("same bytes should share blob: %+v vs %+v", a1, a2)
|
||||
}
|
||||
// 原始文件名仍各自保留
|
||||
if a1.Name != "report.pdf" || a2.Name != "another-name.pdf" {
|
||||
t.Fatalf("original names not preserved: %q / %q", a1.Name, a2.Name)
|
||||
}
|
||||
blobPath := s.FilePath(a1)
|
||||
if _, err := os.Stat(blobPath); err != nil {
|
||||
t.Fatalf("shared private blob missing: %v", err)
|
||||
}
|
||||
|
||||
var blob model.Blob
|
||||
if err := db.First(&blob, "hash = ? AND public = ?", a1.BlobHash, false).Error; err != nil {
|
||||
t.Fatalf("load private blob: %v", err)
|
||||
}
|
||||
if blob.RefCount != 2 {
|
||||
t.Fatalf("refcount want 2, got %d", blob.RefCount)
|
||||
}
|
||||
|
||||
if err := s.DeleteOwn(1, a1.ID); err != nil {
|
||||
t.Fatalf("DeleteOwn 1: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(blobPath); err != nil {
|
||||
t.Fatalf("private blob should survive with one ref: %v", err)
|
||||
}
|
||||
if err := s.DeleteOwn(2, a2.ID); err != nil {
|
||||
t.Fatalf("DeleteOwn 2: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(blobPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("private blob should be removed after last release, stat err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlobPublicPrivateVisibilityIsolation(t *testing.T) {
|
||||
db := newBlobTestDB(t)
|
||||
root := t.TempDir()
|
||||
img := NewUploadService(db, filepath.Join(root, "uploads"))
|
||||
pf := NewPostFileService(db, filepath.Join(root, "private"))
|
||||
if err := img.EnsureDir(); err != nil {
|
||||
t.Fatalf("ensure upload dir: %v", err)
|
||||
}
|
||||
if err := pf.EnsureDir(); err != nil {
|
||||
t.Fatalf("ensure private dir: %v", err)
|
||||
}
|
||||
data := webpFixtureBytes()
|
||||
|
||||
att, err := img.SaveImage(1, bytes.NewReader(data), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage: %v", err)
|
||||
}
|
||||
file, err := pf.SaveDraftFile(1, "x.webp", bytes.NewReader(data), 0)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveDraftFile: %v", err)
|
||||
}
|
||||
if att.BlobHash != file.BlobHash {
|
||||
t.Fatalf("test premise: same bytes should produce same hash")
|
||||
}
|
||||
|
||||
// 同字节在公开/私有命名空间各持一条 blob,互不复用,防止越权读取
|
||||
var pubs, privs int64
|
||||
db.Model(&model.Blob{}).Where("hash = ? AND public = ?", att.BlobHash, true).Count(&pubs)
|
||||
db.Model(&model.Blob{}).Where("hash = ? AND public = ?", att.BlobHash, false).Count(&privs)
|
||||
if pubs != 1 || privs != 1 {
|
||||
t.Fatalf("want separate public/private blobs, pubs=%d privs=%d", pubs, privs)
|
||||
}
|
||||
publicPath := filepath.Join(root, "uploads", filepath.FromSlash(att.URL[len("/uploads/"):]))
|
||||
privatePath := pf.FilePath(file)
|
||||
if publicPath == privatePath {
|
||||
t.Fatal("public and private blob must not share a path")
|
||||
}
|
||||
if _, err := os.Stat(publicPath); err != nil {
|
||||
t.Fatalf("public blob missing: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(privatePath); err != nil {
|
||||
t.Fatalf("private blob missing: %v", err)
|
||||
}
|
||||
}
|
||||
132
backend/service/blob_store.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// 内容寻址存储(content-addressed storage):
|
||||
// 物理文件按【最终存储字节】的 SHA-256 命名,业务行只引用 hash 并各持一份引用计数;
|
||||
// 同内容重复上传不再重复落盘/传输,最后一个引用删除时才回收物理文件。
|
||||
// 公开与私有是独立命名空间(见 model.Blob 注释)。
|
||||
|
||||
// sha256Hex 计算字节的 SHA-256 hex
|
||||
func sha256Hex(data []byte) string {
|
||||
sum := sha256.Sum256(data)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// hashFile 计算文件内容的 SHA-256 hex,整文件流式读取不进内存
|
||||
func hashFile(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// acquireBlobRef 登记一次 blob 引用:行不存在则创建(计数=1),已存在则计数+1。
|
||||
// 并发下靠 (hash, public) 主键冲突重试,保证不丢计数。
|
||||
func acquireBlobRef(db *gorm.DB, hash string, public bool, size int, mimeType, objectID string) error {
|
||||
for {
|
||||
var b model.Blob
|
||||
err := db.Where("hash = ? AND public = ?", hash, public).First(&b).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
b = model.Blob{
|
||||
Hash: hash,
|
||||
Public: public,
|
||||
RefCount: 1,
|
||||
Size: size,
|
||||
MIME: mimeType,
|
||||
ObjectID: objectID,
|
||||
}
|
||||
if err := db.Create(&b).Error; err != nil {
|
||||
if isUniqueConflict(err) {
|
||||
continue // 并发首建:改为走计数+1
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Model(&model.Blob{}).
|
||||
Where("hash = ? AND public = ?", hash, public).
|
||||
UpdateColumn("ref_count", gorm.Expr("ref_count + 1")).Error
|
||||
}
|
||||
}
|
||||
|
||||
// releaseBlobRef 释放一次 blob 引用。计数归零时删行并返回 last=true 与该行快照
|
||||
// (快照里的 ObjectID/Hash 供调用方回收物理对象)。行不存在视为幂等成功。
|
||||
func releaseBlobRef(db *gorm.DB, hash string, public bool) (model.Blob, bool, error) {
|
||||
var removed model.Blob
|
||||
var last bool
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
var b model.Blob
|
||||
// 行锁:postgres 下 FOR UPDATE 串行化同 blob 的并发释放;sqlite 写事务天然串行
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
First(&b, "hash = ? AND public = ?", hash, public).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if b.RefCount <= 1 {
|
||||
result := tx.Where("hash = ? AND public = ? AND ref_count <= 1", hash, public).Delete(&model.Blob{})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected > 0 {
|
||||
removed = b
|
||||
last = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return tx.Model(&model.Blob{}).
|
||||
Where("hash = ? AND public = ?", hash, public).
|
||||
UpdateColumn("ref_count", b.RefCount-1).Error
|
||||
})
|
||||
if err != nil {
|
||||
return model.Blob{}, false, err
|
||||
}
|
||||
return removed, last, nil
|
||||
}
|
||||
|
||||
// placeLocalBlob 把临时文件原子放到内容寻址目标路径:
|
||||
// 目标已存在说明同内容已落盘(字节必然一致),直接丢弃源文件;否则整体 rename。
|
||||
// src 与 dst 同一路径时不做操作。
|
||||
func placeLocalBlob(src, dst string) error {
|
||||
if abs, err := filepath.Abs(src); err == nil {
|
||||
if dstAbs, err := filepath.Abs(dst); err == nil && abs == dstAbs {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Stat(dst); err == nil {
|
||||
if src != dst {
|
||||
_ = os.Remove(src)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
_ = os.Remove(src)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -9,16 +9,17 @@ import (
|
||||
|
||||
// 站点品牌与页脚(公开设置,缺省为空)
|
||||
const (
|
||||
SettingKeySiteWordmark = "site_wordmark"
|
||||
SettingKeySiteSlogan = "site_slogan"
|
||||
SettingKeySiteKeywords = "site_keywords"
|
||||
SettingKeyLogoLightURL = "logo_light_url"
|
||||
SettingKeyLogoDarkURL = "logo_dark_url"
|
||||
SettingKeyFaviconURL = "favicon_url"
|
||||
SettingKeyFooterLinks = "footer_links"
|
||||
SettingKeyBrandMark = "brand_mark"
|
||||
SettingKeyBrandLogoSize = "brand_logo_size"
|
||||
SettingKeyBrandLogoFit = "brand_logo_fit"
|
||||
SettingKeySiteWordmark = "site_wordmark"
|
||||
SettingKeySiteSlogan = "site_slogan"
|
||||
SettingKeySiteKeywords = "site_keywords"
|
||||
SettingKeyLogoLightURL = "logo_light_url"
|
||||
SettingKeyLogoDarkURL = "logo_dark_url"
|
||||
SettingKeyFaviconURL = "favicon_url"
|
||||
SettingKeyFooterLinks = "footer_links"
|
||||
SettingKeyBrandMark = "brand_mark"
|
||||
SettingKeyBrandLogoSize = "brand_logo_size"
|
||||
SettingKeyBrandLogoFit = "brand_logo_fit"
|
||||
SettingKeyBrandSloganVisible = "brand_slogan_visible"
|
||||
|
||||
BrandSlotLight = "logo_light"
|
||||
BrandSlotDark = "logo_dark"
|
||||
@@ -43,6 +44,8 @@ const (
|
||||
BrandLogoSize3x1 = "3x1"
|
||||
BrandLogoSize4x1 = "4x1"
|
||||
BrandLogoSize169 = "16x9"
|
||||
// BrandLogoSizeAuto 原图比例:自由裁剪,页眉图槽按图片原始比例自适应宽度
|
||||
BrandLogoSizeAuto = "auto"
|
||||
|
||||
BrandLogoFitCover = "cover"
|
||||
BrandLogoFitContain = "contain"
|
||||
@@ -114,7 +117,7 @@ func NormalizeBrandLogoSize(raw string) (string, bool) {
|
||||
switch strings.TrimSpace(raw) {
|
||||
case "", BrandLogoSizeSQ:
|
||||
return BrandLogoSizeSQ, true
|
||||
case BrandLogoSize2x1, BrandLogoSize3x1, BrandLogoSize4x1, BrandLogoSize169:
|
||||
case BrandLogoSize2x1, BrandLogoSize3x1, BrandLogoSize4x1, BrandLogoSize169, BrandLogoSizeAuto:
|
||||
return strings.TrimSpace(raw), true
|
||||
default:
|
||||
return "", false
|
||||
@@ -367,6 +370,15 @@ func (s *SettingService) fillBrand(out *PublicSiteSettings) error {
|
||||
out.BrandLogoFit = f
|
||||
}
|
||||
}
|
||||
sv, found, err := s.getValue(SettingKeyBrandSloganVisible)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
out.BrandSloganVisible = sv == "true"
|
||||
} else {
|
||||
out.BrandSloganVisible = true
|
||||
}
|
||||
rawLinks, found, err := s.getValue(SettingKeyFooterLinks)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -483,6 +495,14 @@ func (s *SettingService) SetBrandLogoFit(raw string) error {
|
||||
return s.putValue(SettingKeyBrandLogoFit, v)
|
||||
}
|
||||
|
||||
// SetBrandSloganVisible 控制标语是否在页眉显示;true 为缺省值,存库时删 key 以保持精简。
|
||||
func (s *SettingService) SetBrandSloganVisible(visible bool) error {
|
||||
if visible {
|
||||
return s.deleteKey(SettingKeyBrandSloganVisible)
|
||||
}
|
||||
return s.putValue(SettingKeyBrandSloganVisible, "false")
|
||||
}
|
||||
|
||||
func (s *SettingService) setBrandURL(key, slot, url string) error {
|
||||
u, ok := NormalizeBrandURL(slot, url)
|
||||
if !ok {
|
||||
|
||||
@@ -75,8 +75,8 @@ type RoomView struct {
|
||||
Joined bool `json:"joined"`
|
||||
MyRole string `json:"my_role"`
|
||||
UnreadCount int64 `json:"unread_count"`
|
||||
Pinned bool `json:"pinned"` // 对当前用户是否置顶(含大厅强制)
|
||||
PinForced bool `json:"pin_forced"` // 大厅强制置顶,不可取消
|
||||
Pinned bool `json:"pinned"` // 对当前用户是否置顶(含大厅强制)
|
||||
PinForced bool `json:"pin_forced"` // 大厅强制置顶,不可取消
|
||||
Peer *model.User `json:"peer,omitempty"` // 私聊对方(仅 direct)
|
||||
}
|
||||
|
||||
@@ -114,6 +114,15 @@ func (s *ChatService) membership(tx *gorm.DB, roomID, userID uint) (*model.ChatR
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 过期禁言自动解除:惰性清理,不依赖定时任务
|
||||
if m.Muted && m.MutedUntil != nil && m.MutedUntil.Before(time.Now()) {
|
||||
m.Muted = false
|
||||
m.MutedUntil = nil
|
||||
_ = tx.Model(&model.ChatRoomMember{}).
|
||||
Where("room_id = ? AND user_id = ?", roomID, userID).
|
||||
Select("muted", "muted_until").
|
||||
Updates(map[string]interface{}{"muted": false, "muted_until": nil}).Error
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
@@ -122,7 +131,7 @@ func (s *ChatService) Membership(roomID, userID uint) (*model.ChatRoomMember, er
|
||||
return s.membership(s.db, roomID, userID)
|
||||
}
|
||||
|
||||
// unreadCounts 批量计算访问者在给定群集合中的未读数(消息 ID 大于已读水位、且排除本人发送)
|
||||
// unreadCounts 批量计算访问者在给定群集合中的未读数(消息 ID 大于已读水位、且排除本人发送与系统提示)
|
||||
func (s *ChatService) unreadCounts(userID uint, roomIDs []uint) map[uint]int64 {
|
||||
out := make(map[uint]int64)
|
||||
if userID == 0 || len(roomIDs) == 0 {
|
||||
@@ -132,7 +141,7 @@ func (s *ChatService) unreadCounts(userID uint, roomIDs []uint) map[uint]int64 {
|
||||
s.db.Table("chat_messages AS m").
|
||||
Select("m.room_id AS room_id, count(*) AS cnt").
|
||||
Joins("JOIN chat_room_members AS rm ON rm.room_id = m.room_id AND rm.user_id = ?", userID).
|
||||
Where("m.room_id IN ? AND m.id > rm.last_read_message_id AND m.sender_id <> ? AND m.deleted_at IS NULL AND m.recalled_at IS NULL", roomIDs, userID).
|
||||
Where("m.room_id IN ? AND m.id > rm.last_read_message_id AND m.sender_id <> ? AND m.deleted_at IS NULL AND m.recalled_at IS NULL AND m.is_system = ?", roomIDs, userID, false).
|
||||
Group("m.room_id").
|
||||
Scan(&rows)
|
||||
for _, r := range rows {
|
||||
@@ -758,44 +767,96 @@ func (s *ChatService) Kick(operatorID, roomID, targetID uint, oversee bool) erro
|
||||
return s.removeMember(roomID, targetID)
|
||||
}
|
||||
|
||||
// SetMemberMute 禁言/解禁:群主、群管、全站监管;不可禁言群主或站点站长账号
|
||||
func (s *ChatService) SetMemberMute(operatorID, roomID, targetID uint, muted, oversee bool) error {
|
||||
// DisplayName 取用户群聊展示名(昵称优先,退回用户名);用户不存在/封禁时返回空串
|
||||
func (s *ChatService) DisplayName(userID uint) string {
|
||||
var u model.User
|
||||
if err := s.db.Select("id", "nickname", "username").First(&u, userID).Error; err != nil {
|
||||
return ""
|
||||
}
|
||||
if u.Nickname != "" {
|
||||
return u.Nickname
|
||||
}
|
||||
return u.Username
|
||||
}
|
||||
|
||||
// SendSystemMessage 向房间落库一条系统提示消息(sender_id=0,is_system=true)。
|
||||
// 只推进房间 updated_at,不推进 last_message_id:系统提示不作为会话预览,
|
||||
// 也不参与排序顶置,避免禁言/解禁等管理动作在会话列表伪装成「新消息」。
|
||||
// 失败返回 nil + error。
|
||||
func (s *ChatService) SendSystemMessage(roomID uint, content string) (*model.ChatMessage, error) {
|
||||
msg := &model.ChatMessage{
|
||||
RoomID: roomID,
|
||||
SenderID: 0,
|
||||
Content: content,
|
||||
IsSystem: true,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(msg).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&model.ChatRoom{}).Where("id = ?", roomID).
|
||||
Update("updated_at", time.Now()).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
// SetMemberMute 禁言/解禁:群主、群管、全站监管;不可禁言群主或站点站长账号。
|
||||
// duration 为禁言时长;0 表示永久禁言;muted=false 时忽略 duration 并清空 muted_until。
|
||||
// 返回目标用户昵称(供广播系统提示使用)。
|
||||
func (s *ChatService) SetMemberMute(operatorID, roomID, targetID uint, muted bool, duration time.Duration, oversee bool) (string, error) {
|
||||
room, err := s.getRoom(roomID)
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
if room.RoomType == model.ChatRoomTypeDirect {
|
||||
return ErrChatOwnerOnly
|
||||
return "", ErrChatOwnerOnly
|
||||
}
|
||||
target, err := s.membership(s.db, roomID, targetID)
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
if target.Role == model.ChatRoleOwner {
|
||||
return ErrChatCannotMuteOwner
|
||||
return "", ErrChatCannotMuteOwner
|
||||
}
|
||||
var targetUser model.User
|
||||
if err := s.db.Select("role").First(&targetUser, targetID).Error; err != nil {
|
||||
return ErrChatUserGone
|
||||
if err := s.db.Select("role", "nickname", "username").First(&targetUser, targetID).Error; err != nil {
|
||||
return "", ErrChatUserGone
|
||||
}
|
||||
if targetUser.Role == model.RoleOwner {
|
||||
return ErrChatCannotMuteOwner
|
||||
return "", ErrChatCannotMuteOwner
|
||||
}
|
||||
if !oversee {
|
||||
op, err := s.membership(s.db, roomID, operatorID)
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
if op.Role != model.ChatRoleOwner && op.Role != model.ChatRoleAdmin {
|
||||
return ErrChatMuteDenied
|
||||
return "", ErrChatMuteDenied
|
||||
}
|
||||
if target.Role == model.ChatRoleAdmin && op.Role != model.ChatRoleOwner {
|
||||
return ErrChatMuteDenied
|
||||
return "", ErrChatMuteDenied
|
||||
}
|
||||
}
|
||||
return s.db.Model(&model.ChatRoomMember{}).
|
||||
var mutedUntil *time.Time
|
||||
if muted && duration > 0 {
|
||||
t := time.Now().Add(duration)
|
||||
mutedUntil = &t
|
||||
}
|
||||
if err := s.db.Model(&model.ChatRoomMember{}).
|
||||
Where("room_id = ? AND user_id = ?", roomID, targetID).
|
||||
Select("muted").Update("muted", muted).Error
|
||||
Select("muted", "muted_until").
|
||||
Updates(map[string]interface{}{"muted": muted, "muted_until": mutedUntil}).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
targetName := targetUser.Nickname
|
||||
if targetName == "" {
|
||||
targetName = targetUser.Username
|
||||
}
|
||||
return targetName, nil
|
||||
}
|
||||
|
||||
// SetMemberRole 仅站点站长可任命/撤销群管理员(admin <-> member);不可改群主
|
||||
@@ -970,7 +1031,7 @@ func (s *ChatService) SendMessage(senderID, roomID uint, content string, replyTo
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err := s.db.Preload("Sender").First(msg, msg.ID).Error; err != nil {
|
||||
if err := s.db.Preload("Sender").Preload("Sender.Badges.Badge").First(msg, msg.ID).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
for _, uid := range mentionIDs {
|
||||
@@ -1059,7 +1120,8 @@ func (s *ChatService) ListMessages(userID, roomID, beforeID uint, size int, over
|
||||
q = q.Where("id < ?", beforeID)
|
||||
}
|
||||
var msgs []model.ChatMessage
|
||||
if err := q.Order("id DESC").Limit(size + 1).Preload("Sender").Preload("Recaller").Find(&msgs).Error; err != nil {
|
||||
// Sender.Badges.Badge 嵌套预加载:消息气泡需展示发送者等级与徽章(与成员列表一致)
|
||||
if err := q.Order("id DESC").Limit(size + 1).Preload("Sender").Preload("Sender.Badges.Badge").Preload("Recaller").Find(&msgs).Error; err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
hasMore := len(msgs) > size
|
||||
@@ -1088,7 +1150,7 @@ func (s *ChatService) RecallMessage(operatorID, roomID, messageID uint, oversee
|
||||
return nil, false, err
|
||||
}
|
||||
var msg model.ChatMessage
|
||||
if err := s.db.Where("id = ? AND room_id = ?", messageID, roomID).First(&msg).Error; err != nil {
|
||||
if err := s.db.Where("id = ? AND room_id = ?", messageID, roomID).Preload("Sender").First(&msg).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, false, ErrChatMsgNotFound
|
||||
}
|
||||
@@ -1097,6 +1159,10 @@ func (s *ChatService) RecallMessage(operatorID, roomID, messageID uint, oversee
|
||||
if msg.RecalledAt != nil {
|
||||
return &msg, false, nil // 幂等
|
||||
}
|
||||
// 站长的消息禁止群主/群管/站点消息管撤回(仅全站监管可撤回)
|
||||
if msg.Sender.Role == model.RoleOwner && !oversee {
|
||||
return nil, false, ErrChatRecallDenied
|
||||
}
|
||||
if msg.SenderID == operatorID {
|
||||
if !oversee {
|
||||
if _, err := s.membership(s.db, roomID, operatorID); err != nil {
|
||||
@@ -1115,7 +1181,17 @@ func (s *ChatService) RecallMessage(operatorID, roomID, messageID uint, oversee
|
||||
}
|
||||
msg.RecalledAt = &now
|
||||
msg.RecalledBy = operatorID
|
||||
_ = s.db.Preload("Sender").Preload("Recaller").First(&msg, msg.ID)
|
||||
// 撤回的是房间当前预览消息时,回退 last_message_id 到最近一条未撤回的非系统消息:
|
||||
// 撤回不在会话列表留下「已撤回」预览,也不让房间因此停留在列表前排,避免被当成新消息提醒。
|
||||
var prevID uint
|
||||
_ = s.db.Model(&model.ChatMessage{}).
|
||||
Where("room_id = ? AND deleted_at IS NULL AND recalled_at IS NULL AND is_system = ?", roomID, false).
|
||||
Order("id DESC").Limit(1).
|
||||
Select("id").Row().Scan(&prevID)
|
||||
_ = s.db.Model(&model.ChatRoom{}).
|
||||
Where("id = ? AND last_message_id = ?", roomID, msg.ID).
|
||||
Update("last_message_id", prevID).Error
|
||||
_ = s.db.Preload("Sender").Preload("Sender.Badges.Badge").Preload("Recaller").First(&msg, msg.ID)
|
||||
return &msg, true, nil
|
||||
}
|
||||
|
||||
@@ -1295,13 +1371,13 @@ func (s *ChatService) MarkRead(userID, roomID, messageID uint) error {
|
||||
Update("last_read_message_id", messageID).Error
|
||||
}
|
||||
|
||||
// UnreadSummary 当前用户所有群的未读明细与总数
|
||||
// UnreadSummary 当前用户所有群的未读明细与总数(系统提示消息不计入)
|
||||
func (s *ChatService) UnreadSummary(userID uint) (int64, []UnreadRoom, error) {
|
||||
var rows []UnreadRoom
|
||||
err := s.db.Table("chat_messages AS m").
|
||||
Select("m.room_id AS room_id, count(*) AS cnt").
|
||||
Joins("JOIN chat_room_members AS rm ON rm.room_id = m.room_id AND rm.user_id = ?", userID).
|
||||
Where("m.id > rm.last_read_message_id AND m.sender_id <> ? AND m.deleted_at IS NULL AND m.recalled_at IS NULL", userID).
|
||||
Where("m.id > rm.last_read_message_id AND m.sender_id <> ? AND m.deleted_at IS NULL AND m.recalled_at IS NULL AND m.is_system = ?", userID, false).
|
||||
Group("m.room_id").
|
||||
Scan(&rows).Error
|
||||
if err != nil {
|
||||
|
||||
@@ -44,7 +44,7 @@ func IsNecroReply(lastReplyAt time.Time, afterHours int, now time.Time) bool {
|
||||
|
||||
// CommentService 评论服务
|
||||
type CommentService struct {
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
setting *SettingService
|
||||
}
|
||||
|
||||
@@ -297,6 +297,80 @@ func (s *CommentService) FloorNumber(postID, commentID uint) int {
|
||||
return FloorNumber(s.db, postID, commentID)
|
||||
}
|
||||
|
||||
// CommentAnchor 评论在所属帖子内的相对锚点:
|
||||
// Floor=楼层号(含软删/待审占位,口径同 FloorNumber);IsRoot=true 为主楼,
|
||||
// false 为楼中楼(锚点需附带评论 ID 才能精确定位具体回复)。
|
||||
type CommentAnchor struct {
|
||||
Floor uint `json:"floor"`
|
||||
IsRoot bool `json:"is_root"`
|
||||
}
|
||||
|
||||
// CommentAnchors 批量查询评论锚点(两条 SQL,避免逐行 N+1);
|
||||
// 评论或其主楼已不存在(如整串被彻底删除)时不出现在结果中。
|
||||
func CommentAnchors(db *gorm.DB, ids []uint) map[uint]CommentAnchor {
|
||||
out := make(map[uint]CommentAnchor, len(ids))
|
||||
if db == nil || len(ids) == 0 {
|
||||
return out
|
||||
}
|
||||
// Unscoped:软删/待审评论仍占楼层,与 FloorNumber 同口径
|
||||
var targets []model.Comment
|
||||
if err := db.Unscoped().
|
||||
Select("id", "post_id", "parent_id", "root_id", "created_at").
|
||||
Where("id IN ?", ids).Find(&targets).Error; err != nil {
|
||||
return out
|
||||
}
|
||||
rootIDSet := make(map[uint]struct{}, len(targets))
|
||||
for _, c := range targets {
|
||||
rid := c.ID
|
||||
if c.ParentID != nil && c.RootID != nil {
|
||||
rid = *c.RootID
|
||||
}
|
||||
rootIDSet[rid] = struct{}{}
|
||||
}
|
||||
rootIDs := make([]uint, 0, len(rootIDSet))
|
||||
for rid := range rootIDSet {
|
||||
rootIDs = append(rootIDs, rid)
|
||||
}
|
||||
// 每个主楼之前(按 created_at/id 升序)的主楼数即楼层号 - 1
|
||||
type aheadRow struct {
|
||||
RootID uint
|
||||
Ahead int64
|
||||
}
|
||||
var aheadRows []aheadRow
|
||||
if err := db.Unscoped().Table("comments AS f").
|
||||
Select(`f.id AS root_id,
|
||||
(SELECT COUNT(*) FROM comments c
|
||||
WHERE c.post_id = f.post_id AND c.parent_id IS NULL
|
||||
AND (c.created_at < f.created_at
|
||||
OR (c.created_at = f.created_at AND c.id < f.id))) AS ahead`).
|
||||
Where("f.id IN ? AND f.parent_id IS NULL", rootIDs).
|
||||
Scan(&aheadRows).Error; err != nil {
|
||||
return out
|
||||
}
|
||||
floorByRoot := make(map[uint]uint, len(aheadRows))
|
||||
for _, r := range aheadRows {
|
||||
floorByRoot[r.RootID] = uint(r.Ahead) + 1
|
||||
}
|
||||
for _, c := range targets {
|
||||
isRoot := c.ParentID == nil
|
||||
rid := c.ID
|
||||
if !isRoot && c.RootID != nil {
|
||||
rid = *c.RootID
|
||||
}
|
||||
floor := floorByRoot[rid]
|
||||
if floor == 0 {
|
||||
continue
|
||||
}
|
||||
out[c.ID] = CommentAnchor{Floor: floor, IsRoot: isRoot}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AnchorsByCommentIDs 见包级 CommentAnchors
|
||||
func (s *CommentService) AnchorsByCommentIDs(ids []uint) map[uint]CommentAnchor {
|
||||
return CommentAnchors(s.db, ids)
|
||||
}
|
||||
|
||||
// applyCommentListVisibility 评论流可见性:published,或 pending 且(作者 / 该板可审);
|
||||
// 软删行:已发布的对所有人占位;待审软删仅作者/可审者可见占位。
|
||||
func applyCommentListVisibility(db *gorm.DB, boardID, viewerID uint, actor *Actor) *gorm.DB {
|
||||
@@ -442,6 +516,8 @@ type UserCommentItem struct {
|
||||
PostID uint `json:"post_id"`
|
||||
PostTitle string `json:"post_title"`
|
||||
Content string `json:"content"`
|
||||
Floor uint `json:"floor"` // 所属楼层相对序号(主楼为自身楼层)
|
||||
IsRoot bool `json:"is_root"` // 主楼/楼中楼,供前端拼 #comment-{floor}[-r{id}]
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
@@ -470,6 +546,17 @@ func (s *CommentService) ListByUser(userID uint, page, size int) ([]UserCommentI
|
||||
if items == nil {
|
||||
items = []UserCommentItem{}
|
||||
}
|
||||
ids := make([]uint, 0, len(items))
|
||||
for _, it := range items {
|
||||
ids = append(ids, it.ID)
|
||||
}
|
||||
anchors := s.AnchorsByCommentIDs(ids)
|
||||
for i := range items {
|
||||
if a, ok := anchors[items[i].ID]; ok {
|
||||
items[i].Floor = a.Floor
|
||||
items[i].IsRoot = a.IsRoot
|
||||
}
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
// FollowService 关注服务(仅用户;关注时给对方发通知)
|
||||
type FollowService struct {
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
notif *NotificationService
|
||||
}
|
||||
|
||||
|
||||
@@ -268,8 +268,8 @@ func (s *FriendLinkService) AdminSetStatus(id uint, status, rejectReason string)
|
||||
return err
|
||||
}
|
||||
updates := map[string]interface{}{
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
"status": status,
|
||||
"updated_at": time.Now(),
|
||||
"reject_reason": "",
|
||||
}
|
||||
switch status {
|
||||
|
||||
@@ -24,7 +24,7 @@ const (
|
||||
|
||||
// HeaderNavBuiltinKeys 内置菜单 key 白名单(顺序即默认顺序);
|
||||
// 与前端 lib/headerNav.ts 的 HEADER_NAV_BUILTIN_KEYS 保持一致。
|
||||
var HeaderNavBuiltinKeys = []string{"home", "leaderboard", "library"}
|
||||
var HeaderNavBuiltinKeys = []string{"home", "leaderboard", "library", "snippets"}
|
||||
|
||||
// HeaderNavItem 顶部导航菜单项:
|
||||
//
|
||||
|
||||
@@ -25,18 +25,19 @@ func newHeaderNavTestService(t *testing.T) *SettingService {
|
||||
func TestHeaderNavDefaultWhenMissing(t *testing.T) {
|
||||
s := newHeaderNavTestService(t)
|
||||
got := s.HeaderNav()
|
||||
if len(got) != 3 ||
|
||||
if len(got) != 4 ||
|
||||
got[0] != (HeaderNavItem{Type: HeaderNavItemBuiltin, Key: "home"}) ||
|
||||
got[1] != (HeaderNavItem{Type: HeaderNavItemBuiltin, Key: "leaderboard"}) ||
|
||||
got[2] != (HeaderNavItem{Type: HeaderNavItemBuiltin, Key: "library"}) {
|
||||
got[2] != (HeaderNavItem{Type: HeaderNavItemBuiltin, Key: "library"}) ||
|
||||
got[3] != (HeaderNavItem{Type: HeaderNavItemBuiltin, Key: "snippets"}) {
|
||||
t.Fatalf("missing row should fall back to builtin defaults, got %+v", got)
|
||||
}
|
||||
pub, err := s.Public()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(pub.HeaderNav) != 3 {
|
||||
t.Fatalf("Public().HeaderNav len = %d, want 3", len(pub.HeaderNav))
|
||||
if len(pub.HeaderNav) != 4 {
|
||||
t.Fatalf("Public().HeaderNav len = %d, want 4", len(pub.HeaderNav))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +134,7 @@ func TestNormalizeHeaderNavDedupesBuiltins(t *testing.T) {
|
||||
|
||||
func TestParseHeaderNavJSONTolerant(t *testing.T) {
|
||||
// 坏 JSON 回落默认
|
||||
if got := parseHeaderNavJSON("{bad"); len(got) != 3 {
|
||||
if got := parseHeaderNavJSON("{bad"); len(got) != 4 {
|
||||
t.Fatalf("bad json should fall back to defaults, got %+v", got)
|
||||
}
|
||||
// 空数组 = 全部隐藏
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
hidePwdCookiePrefix = "j13_hp_"
|
||||
hidePwdCookieMaxAge = 30 * 24 * 3600 // 30 天
|
||||
hidePwdCookiePrefix = "j13_hp_"
|
||||
hidePwdCookieMaxAge = 30 * 24 * 3600 // 30 天
|
||||
hidePwdCookieVersion = "1"
|
||||
)
|
||||
|
||||
|
||||
276
backend/service/image_variants.go
Normal file
@@ -0,0 +1,276 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
webpenc "github.com/gen2brain/webp"
|
||||
"golang.org/x/image/draw"
|
||||
xwebp "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// 公开图片变体:GET /api/img?u=<源图URL>&w=<目标宽>
|
||||
// 按宽度白名单实时缩放为 WebP 并持久缓存到 .thumbs/v/,供全站 <img srcset> 消费。
|
||||
// 源内容不可变(上传文件名为随机哈希),变体 URL 可被浏览器/CDN 长期 immutable 缓存。
|
||||
// GIF/SVG/ICO 与「源宽 ≤ 请求宽」一律原样透传:保动效、保矢量、不放大。
|
||||
// 本地源按 mtime 失效;远程对象(/api/media/)ID 即内容,缓存永久有效。
|
||||
|
||||
// VariantWebPQuality 变体 WebP 有损质量(与 MediaThumb 一致)
|
||||
const VariantWebPQuality = 78
|
||||
|
||||
// variantWidths 宽度白名单(与前端 lib/responsiveImage.ts 同值,约 1.5x 步进)
|
||||
var variantWidths = []int{48, 96, 160, 256, 384, 512, 768, 1080, 1536, 1920}
|
||||
|
||||
// IsVariantWidth 是否白名单精确值(非法尺寸 400,防止被刷任意尺寸)
|
||||
func IsVariantWidth(w int) bool {
|
||||
for _, v := range variantWidths {
|
||||
if v == w {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// variantGenLocks 并发生成去重:key=sha1(url).w → 每变体一把锁
|
||||
var variantGenLocks sync.Map
|
||||
|
||||
// extMIME 扩展名 → MIME(含 SVG/ICO 透传类型)
|
||||
func extMIME(ext string) string {
|
||||
switch ext {
|
||||
case ".jpg", ".jpeg":
|
||||
return "image/jpeg"
|
||||
case ".png":
|
||||
return "image/png"
|
||||
case ".webp":
|
||||
return "image/webp"
|
||||
case ".gif":
|
||||
return "image/gif"
|
||||
case ".svg":
|
||||
return "image/svg+xml"
|
||||
case ".ico":
|
||||
return "image/x-icon"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// variantCacheFile 变体缓存路径:.thumbs/v/<sha1(url)>.w<w>.webp
|
||||
func (s *UploadService) variantCacheFile(url string, w int) string {
|
||||
sum := sha1.Sum([]byte(url))
|
||||
name := hex.EncodeToString(sum[:]) + ".w" + strconv.Itoa(w) + ".webp"
|
||||
return filepath.Join(s.dir, ".thumbs", "v", name)
|
||||
}
|
||||
|
||||
// variantCacheFresh 缓存是否新鲜:本地源按 mtime;远程对象(modTime 零值)只看存在
|
||||
func variantCacheFresh(cache string, modTime time.Time) bool {
|
||||
ti, err := os.Stat(cache)
|
||||
if err != nil || ti.IsDir() {
|
||||
return false
|
||||
}
|
||||
return modTime.IsZero() || !ti.ModTime().Before(modTime)
|
||||
}
|
||||
|
||||
// Variant 返回源图指定宽度的变体字节与 MIME。
|
||||
func (s *UploadService) Variant(rawURL string, width int) ([]byte, string, error) {
|
||||
rawURL = strings.TrimSpace(rawURL)
|
||||
if len(rawURL) == 0 || len(rawURL) > 512 {
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
if !IsVariantWidth(width) {
|
||||
return nil, "", errors.New("不支持的尺寸")
|
||||
}
|
||||
|
||||
var (
|
||||
srcData []byte // 远程源预读字节(本地源在锁内读取)
|
||||
srcMIME string
|
||||
srcPath string // 本地源绝对路径
|
||||
modTime time.Time
|
||||
remote bool
|
||||
cache = s.variantCacheFile(rawURL, width)
|
||||
)
|
||||
|
||||
switch {
|
||||
case strings.HasPrefix(rawURL, "/uploads/"):
|
||||
rel := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(rawURL, "/uploads/")))
|
||||
if filepath.IsAbs(rel) || rel == "." || strings.HasPrefix(rel, "..") {
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
dir := filepath.Dir(rel)
|
||||
catOK := false
|
||||
for _, cat := range mediaLibraryCategories {
|
||||
if cat.Dir == dir {
|
||||
catOK = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !catOK {
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(rel))
|
||||
mime := extMIME(ext)
|
||||
if mime == "" {
|
||||
return nil, "", errors.New("非图片")
|
||||
}
|
||||
srcPath = filepath.Join(s.dir, rel)
|
||||
info, err := os.Stat(srcPath)
|
||||
if err != nil || info.IsDir() {
|
||||
return nil, "", errors.New("文件不存在")
|
||||
}
|
||||
// 动图/矢量/图标:无法或无需光栅缩放,原样透传(不占变体缓存)
|
||||
if ext == ".gif" || ext == ".svg" || ext == ".ico" {
|
||||
data, err := os.ReadFile(srcPath)
|
||||
return data, mime, err
|
||||
}
|
||||
srcMIME = mime
|
||||
modTime = info.ModTime()
|
||||
|
||||
case strings.HasPrefix(rawURL, "/api/media/"):
|
||||
if s.ops == nil {
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
id := strings.TrimPrefix(rawURL, "/api/media/")
|
||||
if id == "" || strings.ContainsAny(id, "/?#") || len(id) > 128 {
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
remote = true
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
r, mime, e := s.ops.OpenObject(ctx, id, true)
|
||||
if e != nil {
|
||||
return nil, "", errors.New("文件暂不可用")
|
||||
}
|
||||
defer r.Close()
|
||||
switch mime {
|
||||
case "image/jpeg", "image/png", "image/webp":
|
||||
case "image/gif", "image/svg+xml", "image/x-icon", "image/vnd.microsoft.icon":
|
||||
data, err := io.ReadAll(r)
|
||||
return data, mime, err
|
||||
default:
|
||||
return nil, "", errors.New("非图片")
|
||||
}
|
||||
srcData, e = io.ReadAll(r)
|
||||
if e != nil {
|
||||
return nil, "", e
|
||||
}
|
||||
srcMIME = mime
|
||||
|
||||
default:
|
||||
return nil, "", errors.New("无效地址")
|
||||
}
|
||||
|
||||
// 快速路径:缓存已新鲜直接返回(无锁)
|
||||
if variantCacheFresh(cache, modTime) {
|
||||
if data, err := os.ReadFile(cache); err == nil {
|
||||
return data, "image/webp", nil
|
||||
}
|
||||
}
|
||||
|
||||
// 并发生成去重:同 url+w 只生成一次
|
||||
sum := sha1.Sum([]byte(rawURL))
|
||||
key := hex.EncodeToString(sum[:]) + ".w" + strconv.Itoa(width)
|
||||
mu, _ := variantGenLocks.LoadOrStore(key, &sync.Mutex{})
|
||||
lk := mu.(*sync.Mutex)
|
||||
lk.Lock()
|
||||
defer lk.Unlock()
|
||||
|
||||
// double-check:等锁期间可能已由他人生成
|
||||
if variantCacheFresh(cache, modTime) {
|
||||
if data, err := os.ReadFile(cache); err == nil {
|
||||
return data, "image/webp", nil
|
||||
}
|
||||
}
|
||||
|
||||
if !remote {
|
||||
data, err := os.ReadFile(srcPath)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
srcData = data
|
||||
}
|
||||
|
||||
out, m, err := variantFromBytes(srcData, srcMIME, width)
|
||||
if err != nil {
|
||||
return nil, "", err // 如动图 WebP,调用方回退原图
|
||||
}
|
||||
// 仅 WebP 变体积缓存(小图透传不落盘);失败仅影响下次重复生成,不阻断响应
|
||||
if m == "image/webp" {
|
||||
_ = atomicWriteFile(cache, out)
|
||||
}
|
||||
return out, m, nil
|
||||
}
|
||||
|
||||
// variantFromBytes 源字节 → 目标变体:解码失败报错(调用方回退原图);
|
||||
// 源宽 ≤ 目标宽 → 原字节透传(不放大);否则按目标宽等比缩放为 WebP。
|
||||
func variantFromBytes(srcData []byte, srcMIME string, width int) ([]byte, string, error) {
|
||||
img, err := decodeImageBytes(srcData, srcMIME == "image/webp")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
b := img.Bounds()
|
||||
if b.Dx() <= width {
|
||||
return srcData, srcMIME, nil
|
||||
}
|
||||
nh := max(1, b.Dy()*width/b.Dx())
|
||||
dst := scaleImage(img, width, nh)
|
||||
out, err := encodeLossyWebP(dst, VariantWebPQuality)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return out, "image/webp", nil
|
||||
}
|
||||
|
||||
// ---------- 与 MediaThumb 共用的图片处理核心 ----------
|
||||
|
||||
// decodeImageBytes 解码图片字节;WebP 走 x/image/webp 解码器
|
||||
func decodeImageBytes(data []byte, isWebP bool) (image.Image, error) {
|
||||
if isWebP {
|
||||
return xwebp.Decode(bytes.NewReader(data))
|
||||
}
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
return img, err
|
||||
}
|
||||
|
||||
// scaleImage CatmullRom 高质量缩放到指定宽高
|
||||
func scaleImage(img image.Image, nw, nh int) *image.RGBA {
|
||||
dst := image.NewRGBA(image.Rect(0, 0, nw, nh))
|
||||
draw.CatmullRom.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Src, nil)
|
||||
return dst
|
||||
}
|
||||
|
||||
// encodeLossyWebP 有损 WebP 编码
|
||||
func encodeLossyWebP(img image.Image, quality int) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := webpenc.Encode(&buf, img, webpenc.Options{Quality: quality}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// atomicWriteFile 临时文件 + rename 原子落盘
|
||||
func atomicWriteFile(path string, data []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".partial"
|
||||
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
282
backend/service/image_variants_test.go
Normal file
@@ -0,0 +1,282 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/config"
|
||||
webpenc "github.com/gen2brain/webp"
|
||||
xwebp "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// solidImg 生成渐变纯色测试图
|
||||
func solidImg(w, h int) *image.RGBA {
|
||||
src := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
src.Set(x, y, color.RGBA{uint8(x % 256), uint8(y % 256), 128, 255})
|
||||
}
|
||||
}
|
||||
return src
|
||||
}
|
||||
|
||||
// writeVariantSource 把按编码器生成的文件写到 uploads 目录
|
||||
func writeVariantSource(t *testing.T, dir, url string, encode func(io.Writer) error) {
|
||||
t.Helper()
|
||||
abs := filepath.Join(dir, filepath.FromSlash(strings.TrimPrefix(url, "/uploads/")))
|
||||
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
f, err := os.Create(abs)
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := encode(f); err != nil {
|
||||
t.Fatalf("encode: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeJPEG(img image.Image) func(io.Writer) error {
|
||||
return func(w io.Writer) error {
|
||||
return jpeg.Encode(w, img, &jpeg.Options{Quality: 85})
|
||||
}
|
||||
}
|
||||
|
||||
func encodePNG(img image.Image) func(io.Writer) error {
|
||||
return func(w io.Writer) error {
|
||||
return png.Encode(w, img)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeWebP(img image.Image) func(io.Writer) error {
|
||||
return func(w io.Writer) error {
|
||||
return webpenc.Encode(w, img, webpenc.Options{Quality: 85})
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGIF(img image.Image) func(io.Writer) error {
|
||||
return func(w io.Writer) error {
|
||||
return gif.Encode(w, img, nil)
|
||||
}
|
||||
}
|
||||
|
||||
// decodeVariant 解码返回的 WebP 变体
|
||||
func decodeVariant(t *testing.T, data []byte) image.Image {
|
||||
t.Helper()
|
||||
img, err := xwebp.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatalf("decode variant webp: %v", err)
|
||||
}
|
||||
return img
|
||||
}
|
||||
|
||||
func TestIsVariantWidth(t *testing.T) {
|
||||
if !IsVariantWidth(48) || !IsVariantWidth(1920) {
|
||||
t.Fatal("whitelist endpoints should be valid")
|
||||
}
|
||||
if IsVariantWidth(100) || IsVariantWidth(0) || IsVariantWidth(-48) {
|
||||
t.Fatal("non-whitelist width should be invalid")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantRejectsInvalidInput(t *testing.T) {
|
||||
s, _ := newUploadTestService(t)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
url string
|
||||
w int
|
||||
}{
|
||||
{"非法尺寸", "/uploads/images/a.webp", 100},
|
||||
{"路径穿越", "/uploads/images/../../etc/passwd", 96},
|
||||
{"非白名单目录", "/uploads/secret/a.webp", 96},
|
||||
{"非图片扩展名", "/uploads/images/a.txt", 96},
|
||||
{"外部地址", "https://evil.com/a.webp", 96},
|
||||
{"空地址", "", 96},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, _, err := s.Variant(tc.url, tc.w); err == nil {
|
||||
t.Fatal("want error, got nil")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantMissingFile(t *testing.T) {
|
||||
s, _ := newUploadTestService(t)
|
||||
if _, _, err := s.Variant("/uploads/images/missing.webp", 96); err == nil {
|
||||
t.Fatal("missing source should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantPassthroughSmallImage(t *testing.T) {
|
||||
s, dir := newUploadTestService(t)
|
||||
url := "/uploads/images/small.webp"
|
||||
writeVariantSource(t, dir, url, encodeWebP(solidImg(48, 48)))
|
||||
|
||||
data, m, err := s.Variant(url, 96)
|
||||
if err != nil {
|
||||
t.Fatalf("variant: %v", err)
|
||||
}
|
||||
if m != "image/webp" {
|
||||
t.Fatalf("want webp mime, got %s", m)
|
||||
}
|
||||
src, _ := os.ReadFile(filepath.Join(dir, filepath.FromSlash("images/small.webp")))
|
||||
if !bytes.Equal(data, src) {
|
||||
t.Fatal("small image should be returned byte-for-byte")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantResizesByWidthLandscape(t *testing.T) {
|
||||
s, dir := newUploadTestService(t)
|
||||
url := "/uploads/images/wide.jpg"
|
||||
writeVariantSource(t, dir, url, encodeJPEG(solidImg(1000, 500)))
|
||||
|
||||
data, m, err := s.Variant(url, 384)
|
||||
if err != nil {
|
||||
t.Fatalf("variant: %v", err)
|
||||
}
|
||||
if m != "image/webp" {
|
||||
t.Fatalf("want webp, got %s", m)
|
||||
}
|
||||
b := decodeVariant(t, data).Bounds()
|
||||
if b.Dx() != 384 || b.Dy() != 192 {
|
||||
t.Fatalf("want 384x192, got %dx%d", b.Dx(), b.Dy())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantResizesByWidthPortrait(t *testing.T) {
|
||||
s, dir := newUploadTestService(t)
|
||||
url := "/uploads/images/tall.png"
|
||||
writeVariantSource(t, dir, url, encodePNG(solidImg(500, 1000)))
|
||||
|
||||
data, _, err := s.Variant(url, 256)
|
||||
if err != nil {
|
||||
t.Fatalf("variant: %v", err)
|
||||
}
|
||||
b := decodeVariant(t, data).Bounds()
|
||||
if b.Dx() != 256 || b.Dy() != 512 {
|
||||
t.Fatalf("want 256x512, got %dx%d", b.Dx(), b.Dy())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantPassthroughGIFSVGICO(t *testing.T) {
|
||||
s, dir := newUploadTestService(t)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
url string
|
||||
mime string
|
||||
body []byte
|
||||
}{
|
||||
{"gif", "/uploads/images/a.gif", "image/gif", nil},
|
||||
{"svg", "/uploads/images/a.svg", "image/svg+xml", []byte("<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>")},
|
||||
{"ico", "/uploads/images/a.ico", "image/x-icon", []byte("\x00\x00\x01\x00")},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if tc.body != nil {
|
||||
writeVariantSource(t, dir, tc.url, func(w io.Writer) error {
|
||||
_, err := w.Write(tc.body)
|
||||
return err
|
||||
})
|
||||
} else {
|
||||
writeVariantSource(t, dir, tc.url, encodeGIF(solidImg(16, 16)))
|
||||
}
|
||||
data, m, err := s.Variant(tc.url, 96)
|
||||
if err != nil {
|
||||
t.Fatalf("variant: %v", err)
|
||||
}
|
||||
if m != tc.mime {
|
||||
t.Fatalf("want %s, got %s", tc.mime, m)
|
||||
}
|
||||
src, _ := os.ReadFile(filepath.Join(dir, filepath.FromSlash(strings.TrimPrefix(tc.url, "/uploads/"))))
|
||||
if !bytes.Equal(data, src) {
|
||||
t.Fatalf("%s should pass through unchanged", tc.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantCachedAndReused(t *testing.T) {
|
||||
s, dir := newUploadTestService(t)
|
||||
url := "/uploads/images/cache.jpg"
|
||||
writeVariantSource(t, dir, url, encodeJPEG(solidImg(1000, 500)))
|
||||
|
||||
first, m, err := s.Variant(url, 384)
|
||||
if err != nil {
|
||||
t.Fatalf("first variant: %v", err)
|
||||
}
|
||||
if m != "image/webp" {
|
||||
t.Fatalf("want webp, got %s", m)
|
||||
}
|
||||
cache := s.variantCacheFile(url, 384)
|
||||
if info, err := os.Stat(cache); err != nil || info.IsDir() {
|
||||
t.Fatalf("cache file should exist: %v", err)
|
||||
}
|
||||
second, _, err := s.Variant(url, 384)
|
||||
if err != nil {
|
||||
t.Fatalf("second variant: %v", err)
|
||||
}
|
||||
if !bytes.Equal(first, second) {
|
||||
t.Fatal("cached variant should be byte-identical")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantCacheFreshness(t *testing.T) {
|
||||
_, dir := newUploadTestService(t)
|
||||
cache := filepath.Join(dir, ".thumbs", "v", "x.webp")
|
||||
if err := os.MkdirAll(filepath.Dir(cache), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(cache, []byte("data"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 远程对象:modTime 零值,存在即新鲜
|
||||
if !variantCacheFresh(cache, time.Time{}) {
|
||||
t.Fatal("remote cache should be fresh when file exists")
|
||||
}
|
||||
// 本地源:mtime 新于缓存 → 不新鲜
|
||||
future := time.Now().Add(1 * time.Hour)
|
||||
if variantCacheFresh(cache, future) {
|
||||
t.Fatal("cache should be stale vs newer source mtime")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantRemoteRejectsBadID(t *testing.T) {
|
||||
s, _ := newUploadTestService(t)
|
||||
s.ops = NewOperations(s.db, &config.Config{})
|
||||
|
||||
if _, _, err := s.Variant("/api/media/bad/id", 96); err == nil {
|
||||
t.Fatal("id with slash should be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantRemoteUnavailable(t *testing.T) {
|
||||
s, _ := newUploadTestService(t)
|
||||
s.ops = NewOperations(s.db, &config.Config{})
|
||||
|
||||
// 表不存在/对象不存在:统一对外“暂不可用”,不泄漏细节
|
||||
if _, _, err := s.Variant("/api/media/deadbeef", 96); err == nil {
|
||||
t.Fatal("missing remote object should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantRemoteWithoutOps(t *testing.T) {
|
||||
s, _ := newUploadTestService(t)
|
||||
if _, _, err := s.Variant("/api/media/abc", 96); err == nil {
|
||||
t.Fatal("remote url without ops wired should error")
|
||||
}
|
||||
}
|
||||
@@ -38,9 +38,9 @@ func TestEarnedPointsWindowAndExclusions(t *testing.T) {
|
||||
{UserID: a, Delta: 5, Reason: model.PointReasonCheckin, Balance: 5, CreatedAt: now},
|
||||
{UserID: a, Delta: 3, Reason: model.PointReasonReplyReward, Balance: 8, CreatedAt: now},
|
||||
{UserID: a, Delta: 2, Reason: model.PointReasonStreakBonus, Balance: 10, CreatedAt: now.Add(-time.Hour)},
|
||||
{UserID: a, Delta: -3, Reason: model.PointReasonUnlockPost, Balance: 7, CreatedAt: now}, // 支出不计
|
||||
{UserID: users[1].ID, Delta: 8, Reason: model.PointReasonBountyRefund, Balance: 8, CreatedAt: now}, // 退回不计
|
||||
{UserID: users[2].ID, Delta: 5, Reason: model.PointReasonCheckin, Balance: 5, CreatedAt: now}, // 封禁不计
|
||||
{UserID: a, Delta: -3, Reason: model.PointReasonUnlockPost, Balance: 7, CreatedAt: now}, // 支出不计
|
||||
{UserID: users[1].ID, Delta: 8, Reason: model.PointReasonBountyRefund, Balance: 8, CreatedAt: now}, // 退回不计
|
||||
{UserID: users[2].ID, Delta: 5, Reason: model.PointReasonCheckin, Balance: 5, CreatedAt: now}, // 封禁不计
|
||||
{UserID: d, Delta: 5, Reason: model.PointReasonCheckin, Balance: 5, CreatedAt: weekAgo.Add(-time.Hour)}, // 窗口外
|
||||
}
|
||||
if err := db.Create(&ledgers).Error; err != nil {
|
||||
|
||||
@@ -102,7 +102,7 @@ type LegacyUserPreview struct {
|
||||
Nickname string `json:"nickname"`
|
||||
Posts int `json:"posts"`
|
||||
Comments int `json:"comments"`
|
||||
Exists bool `json:"exists"` // 本站已有同名账号(导入时自动跳过建号)
|
||||
Exists bool `json:"exists"` // 本站已有同名账号(导入时自动跳过建号)
|
||||
HasAvatar bool `json:"has_avatar"`
|
||||
}
|
||||
|
||||
@@ -142,8 +142,8 @@ type LegacyUserReport struct {
|
||||
|
||||
// LegacyBoardReport 板块导入明细
|
||||
type LegacyBoardReport struct {
|
||||
Created int `json:"created"` // 新建(预检时为「将新建」)
|
||||
Reused int `json:"reused"` // 复用同名已有板块
|
||||
Created int `json:"created"` // 新建(预检时为「将新建」)
|
||||
Reused int `json:"reused"` // 复用同名已有板块
|
||||
Names []string `json:"names,omitempty"` // 新建板块名
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ type LegacyBoardReport struct {
|
||||
type LegacyPostReport struct {
|
||||
Total int `json:"total"`
|
||||
Imported int `json:"imported"`
|
||||
Skipped int `json:"skipped"` // 已导入过(去重记录)
|
||||
Skipped int `json:"skipped"` // 已导入过(去重记录)
|
||||
Excluded int `json:"excluded"` // 手动排除
|
||||
ExcludedDetail []string `json:"excluded_detail,omitempty"`
|
||||
PollsSkipped int `json:"polls_skipped"`
|
||||
@@ -751,19 +751,19 @@ func (s *LegacyImportService) importPosts(oldDB *gorm.DB, boardMap map[uint]uint
|
||||
continue
|
||||
}
|
||||
post := model.Post{
|
||||
BoardID: boardID,
|
||||
UserID: authorID,
|
||||
Title: truncateRunesN(title, 256),
|
||||
Content: content,
|
||||
Tags: p.Tags,
|
||||
PostType: model.NormalizePostType(p.PostType), // question→question,normal→discussion
|
||||
Pinned: p.Pinned,
|
||||
Recommended: p.Featured,
|
||||
Status: model.ContentStatusPublished,
|
||||
LikeCount: p.LikeCount,
|
||||
ViewCount: p.ViewCount,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UpdatedAt: p.UpdatedAt,
|
||||
BoardID: boardID,
|
||||
UserID: authorID,
|
||||
Title: truncateRunesN(title, 256),
|
||||
Content: content,
|
||||
Tags: p.Tags,
|
||||
PostType: model.NormalizePostType(p.PostType), // question→question,normal→discussion
|
||||
Pinned: p.Pinned,
|
||||
Recommended: p.Featured,
|
||||
Status: model.ContentStatusPublished,
|
||||
LikeCount: p.LikeCount,
|
||||
ViewCount: p.ViewCount,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UpdatedAt: p.UpdatedAt,
|
||||
}
|
||||
if err := s.db.Create(&post).Error; err != nil {
|
||||
out.Failed = append(out.Failed, fmt.Sprintf("%s (写入失败: %v)", title, err))
|
||||
|
||||
@@ -136,9 +136,9 @@ func TestLegacyImportSelectiveRun(t *testing.T) {
|
||||
svc, oldPath, avatarZip, imagesZip, adminID, hallMembers := newLegacyTestEnv(t)
|
||||
opts := LegacyImportOptions{
|
||||
WithContent: true,
|
||||
SkipUserIDs: map[uint]bool{2: true, 3: true}, // bob / carol 不建号
|
||||
UserTargetNames: map[uint]string{2: "admin"}, // bob 的内容归到已有账号 admin
|
||||
SkipCommentIDs: map[uint]bool{202: true}, // 排除 alice 在 #101 的评论
|
||||
SkipUserIDs: map[uint]bool{2: true, 3: true}, // bob / carol 不建号
|
||||
UserTargetNames: map[uint]string{2: "admin"}, // bob 的内容归到已有账号 admin
|
||||
SkipCommentIDs: map[uint]bool{202: true}, // 排除 alice 在 #101 的评论
|
||||
}
|
||||
rep, err := svc.ImportFromFiles(oldPath, avatarZip, imagesZip, opts, adminID)
|
||||
if err != nil {
|
||||
@@ -241,8 +241,8 @@ func TestLegacyImportSelectiveRun(t *testing.T) {
|
||||
func TestLegacyImportSkipPostCascades(t *testing.T) {
|
||||
svc, oldPath, avatarZip, imagesZip, adminID, _ := newLegacyTestEnv(t)
|
||||
opts := LegacyImportOptions{
|
||||
WithContent: true,
|
||||
SkipPostIDs: map[uint]bool{101: true}, // #101 排除 → 其评论 #202 自动跳过
|
||||
WithContent: true,
|
||||
SkipPostIDs: map[uint]bool{101: true}, // #101 排除 → 其评论 #202 自动跳过
|
||||
}
|
||||
rep, err := svc.ImportFromFiles(oldPath, avatarZip, imagesZip, opts, adminID)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -44,7 +46,16 @@ func LibraryExtAllowed(ext string) bool {
|
||||
|
||||
// 写入时显式列出字段(独立 Select 参数,同 sitePageWriteFields)
|
||||
var libraryDocWriteFields = []string{
|
||||
"Slug", "Title", "Description", "CoverURL", "Published", "SortOrder", "EntriesAuto",
|
||||
"Slug", "Title", "Description", "CoverURL", "CoverWidth", "CoverHeight",
|
||||
"Published", "SortOrder", "EntriesAuto", "Author", "CreatorID",
|
||||
}
|
||||
|
||||
// LibraryCreator 条目创建者摘要(仅列表/详情展示所需字段;用户已注销时为 nil)
|
||||
type LibraryCreator struct {
|
||||
ID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Nickname string `json:"nickname"`
|
||||
Avatar string `json:"avatar"`
|
||||
}
|
||||
|
||||
// LibraryDocDetail 条目 + 文件列表 + 章节树(管理端与公开详情共用)
|
||||
@@ -53,27 +64,34 @@ type LibraryDocDetail struct {
|
||||
Deleted bool `json:"deleted"` // 软删标记(DeletedAt json:"-" 不出模型)
|
||||
Files []model.LibraryFile `json:"files"`
|
||||
Sections []model.LibrarySection `json:"sections"`
|
||||
Creator *LibraryCreator `json:"creator,omitempty"` // 创建者摘要(0/已注销=nil)
|
||||
}
|
||||
|
||||
// LibraryDocListItem 公开目录条目(不含 description 全文,含文件概要)
|
||||
// LibraryDocListItem 公开目录条目(description 纯文本截断,含文件概要)
|
||||
type LibraryDocListItem struct {
|
||||
ID uint `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
FileCount int `json:"file_count"`
|
||||
Files []model.LibraryFile `json:"files"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Author string `json:"author"`
|
||||
Description string `json:"description"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
FileCount int `json:"file_count"`
|
||||
Files []model.LibraryFile `json:"files"`
|
||||
Creator *LibraryCreator `json:"creator,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// LibraryInput 创建/更新书库条目入参
|
||||
type LibraryInput struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Author string `json:"author"` // 书籍作者(自由文本,可空)
|
||||
Description string `json:"description"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
CoverWidth int `json:"cover_width"` // 封面自然宽(0=未知)
|
||||
CoverHeight int `json:"cover_height"` // 封面自然高(0=未知)
|
||||
Published *bool `json:"published"`
|
||||
SortOrder *int `json:"sort_order"`
|
||||
EntriesAuto *bool `json:"entries_auto"` // 全章节条目卡模式(nil=不修改)
|
||||
@@ -99,6 +117,11 @@ func (in *LibraryInput) normalize() error {
|
||||
return errors.New("标题不能超过 200 字")
|
||||
}
|
||||
|
||||
in.Author = strings.TrimSpace(in.Author)
|
||||
if utf8.RuneCountInString(in.Author) > 100 {
|
||||
return errors.New("作者不能超过 100 字")
|
||||
}
|
||||
|
||||
in.Description = strings.TrimSpace(in.Description)
|
||||
if utf8.RuneCountInString(in.Description) > libraryDescriptionMax {
|
||||
return errors.New("介绍不能超过 20000 字")
|
||||
@@ -115,8 +138,17 @@ func (in *LibraryInput) normalize() error {
|
||||
func (in *LibraryInput) applyTo(d *model.LibraryDoc) {
|
||||
d.Slug = in.Slug
|
||||
d.Title = in.Title
|
||||
d.Author = in.Author
|
||||
d.Description = in.Description
|
||||
d.CoverURL = in.CoverURL
|
||||
// 封面清空时一并清除尺寸;有封面但未传尺寸时保留 0(前端回退运行时探测)
|
||||
if in.CoverURL == "" {
|
||||
d.CoverWidth = 0
|
||||
d.CoverHeight = 0
|
||||
} else {
|
||||
d.CoverWidth = in.CoverWidth
|
||||
d.CoverHeight = in.CoverHeight
|
||||
}
|
||||
if in.Published != nil {
|
||||
d.Published = *in.Published
|
||||
}
|
||||
@@ -130,9 +162,10 @@ func (in *LibraryInput) applyTo(d *model.LibraryDoc) {
|
||||
|
||||
// LibraryService 书库服务(条目 CRUD + 文件落盘/下载/预览)
|
||||
type LibraryService struct {
|
||||
db *gorm.DB
|
||||
dir string // data/library(绝不放 data/uploads:静态目录会按扩展名原样 serve html)
|
||||
setting *SettingService
|
||||
db *gorm.DB
|
||||
dir string // data/library(绝不放 data/uploads:静态目录会按扩展名原样 serve html)
|
||||
uploadsDir string // data/uploads:封面回填时解析本地封面图
|
||||
setting *SettingService
|
||||
}
|
||||
|
||||
func NewLibraryService(db *gorm.DB, dataDir string) *LibraryService {
|
||||
@@ -145,6 +178,12 @@ func (s *LibraryService) WithSetting(setting *SettingService) *LibraryService {
|
||||
return s
|
||||
}
|
||||
|
||||
// WithUploadsDir 注入上传根目录(封面回填用:把 /uploads/... 封面 URL 解析为本地文件)
|
||||
func (s *LibraryService) WithUploadsDir(uploadsDir string) *LibraryService {
|
||||
s.uploadsDir = uploadsDir
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *LibraryService) EnsureDir() error {
|
||||
return os.MkdirAll(s.dir, 0o755)
|
||||
}
|
||||
@@ -224,6 +263,7 @@ func (s *LibraryService) attachFiles(docs []model.LibraryDoc) []LibraryDocDetail
|
||||
for _, sec := range sections {
|
||||
secByDoc[sec.DocID] = append(secByDoc[sec.DocID], sec)
|
||||
}
|
||||
creatorByID := s.creatorMap(docs)
|
||||
for _, d := range docs {
|
||||
fs := byDoc[d.ID]
|
||||
if fs == nil {
|
||||
@@ -233,12 +273,40 @@ func (s *LibraryService) attachFiles(docs []model.LibraryDoc) []LibraryDocDetail
|
||||
if ss == nil {
|
||||
ss = []model.LibrarySection{}
|
||||
}
|
||||
out = append(out, LibraryDocDetail{LibraryDoc: d, Deleted: d.DeletedAt.Valid, Files: fs, Sections: ss})
|
||||
out = append(out, LibraryDocDetail{
|
||||
LibraryDoc: d, Deleted: d.DeletedAt.Valid, Files: fs, Sections: ss,
|
||||
Creator: creatorByID[d.CreatorID],
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *LibraryService) Create(in *LibraryInput) (*model.LibraryDoc, error) {
|
||||
// creatorMap 批量取条目创建者摘要(一条 SQL,避免列表 N+1;已注销用户查不到即缺省)
|
||||
func (s *LibraryService) creatorMap(docs []model.LibraryDoc) map[uint]*LibraryCreator {
|
||||
ids := make([]uint, 0, len(docs))
|
||||
seen := map[uint]bool{}
|
||||
for _, d := range docs {
|
||||
if d.CreatorID > 0 && !seen[d.CreatorID] {
|
||||
seen[d.CreatorID] = true
|
||||
ids = append(ids, d.CreatorID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return map[uint]*LibraryCreator{}
|
||||
}
|
||||
var users []model.User
|
||||
if err := s.db.Select("id, username, nickname, avatar").Where("id IN ?", ids).Find(&users).Error; err != nil {
|
||||
return map[uint]*LibraryCreator{}
|
||||
}
|
||||
m := make(map[uint]*LibraryCreator, len(users))
|
||||
for i := range users {
|
||||
u := &users[i]
|
||||
m[u.ID] = &LibraryCreator{ID: u.ID, Username: u.Username, Nickname: u.Nickname, Avatar: u.Avatar}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *LibraryService) Create(in *LibraryInput, creatorID ...uint) (*model.LibraryDoc, error) {
|
||||
if err := in.normalize(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -253,6 +321,9 @@ func (s *LibraryService) Create(in *LibraryInput) (*model.LibraryDoc, error) {
|
||||
return nil, errors.New("该地址已被已删除条目占用,可在书库管理列表中彻底删除后重新使用")
|
||||
}
|
||||
d := &model.LibraryDoc{Published: false, SortOrder: 0}
|
||||
if len(creatorID) > 0 {
|
||||
d.CreatorID = creatorID[0]
|
||||
}
|
||||
in.applyTo(d)
|
||||
if err := s.db.Select(libraryDocWriteFields).Create(d).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -279,12 +350,15 @@ func (s *LibraryService) Update(id uint, in *LibraryInput) (*model.LibraryDoc, e
|
||||
return nil, errors.New("该地址已被已删除条目占用,可在书库管理列表中彻底删除后重新使用")
|
||||
}
|
||||
in.applyTo(&d)
|
||||
// map 更新确保 false/空串写入(同 SitePage.Update)
|
||||
// map 更新确保 false/空串写入(同 SitePage.Update);creator_id 创建后不变,不在此列
|
||||
if err := s.db.Model(&model.LibraryDoc{}).Where("id = ?", d.ID).Updates(map[string]interface{}{
|
||||
"slug": d.Slug,
|
||||
"title": d.Title,
|
||||
"author": d.Author,
|
||||
"description": d.Description,
|
||||
"cover_url": d.CoverURL,
|
||||
"cover_width": d.CoverWidth,
|
||||
"cover_height": d.CoverHeight,
|
||||
"published": d.Published,
|
||||
"sort_order": d.SortOrder,
|
||||
"entries_auto": d.EntriesAuto,
|
||||
@@ -294,6 +368,77 @@ func (s *LibraryService) Update(id uint, in *LibraryInput) (*model.LibraryDoc, e
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
// resolveCoverPath 把 /uploads/... 封面 URL 解析为本地绝对路径;外链返回空串
|
||||
func (s *LibraryService) resolveCoverPath(coverURL string) (string, bool) {
|
||||
rel := strings.TrimPrefix(strings.TrimSpace(coverURL), "/uploads/")
|
||||
if rel == "" || rel == coverURL || strings.Contains(rel, "..") {
|
||||
return "", false
|
||||
}
|
||||
abs := filepath.Join(s.uploadsDir, filepath.FromSlash(rel))
|
||||
root := filepath.Clean(s.uploadsDir)
|
||||
clean := filepath.Clean(abs)
|
||||
if clean != root && !strings.HasPrefix(clean, root+string(os.PathSeparator)) {
|
||||
return "", false
|
||||
}
|
||||
return clean, true
|
||||
}
|
||||
|
||||
// measureCoverReader 从图片流读取自然宽高(复用上传层的格式探测与尺寸解码)
|
||||
func measureCoverReader(r io.Reader) (w, h int, err error) {
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
format, err := detectImageFormat(data)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return decodeImageSizeReader(bytes.NewReader(data), format.mime)
|
||||
}
|
||||
|
||||
// ensureCoverDimensions 若条目有封面但未存自然宽高,则测量并写回库(幂等:已有尺寸直接跳过)。
|
||||
// 用于读路径懒回填,避免独立运维接口:首次访问后尺寸即落库,后续 SSR 首帧直接判定横竖版。
|
||||
func (s *LibraryService) ensureCoverDimensions(d *model.LibraryDoc) {
|
||||
if d.CoverURL == "" || (d.CoverWidth > 0 && d.CoverHeight > 0) || s.uploadsDir == "" {
|
||||
return
|
||||
}
|
||||
url := strings.TrimSpace(d.CoverURL)
|
||||
var reader io.ReadCloser
|
||||
switch {
|
||||
case strings.HasPrefix(url, "/uploads/"):
|
||||
abs, ok := s.resolveCoverPath(url)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
f, err := os.Open(abs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
reader = f
|
||||
case strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://"):
|
||||
client := &http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
reader = resp.Body
|
||||
default:
|
||||
return
|
||||
}
|
||||
w, h, err := measureCoverReader(reader)
|
||||
reader.Close()
|
||||
if err != nil || w <= 0 || h <= 0 {
|
||||
return
|
||||
}
|
||||
if err := s.db.Model(d).Updates(map[string]interface{}{
|
||||
"cover_width": w,
|
||||
"cover_height": h,
|
||||
}).Error; err != nil {
|
||||
return
|
||||
}
|
||||
d.CoverWidth, d.CoverHeight = w, h
|
||||
}
|
||||
|
||||
func (s *LibraryService) Delete(id uint) error {
|
||||
result := s.db.Delete(&model.LibraryDoc{}, id)
|
||||
if result.Error != nil {
|
||||
@@ -349,8 +494,9 @@ func (s *LibraryService) ListPublished() ([]LibraryDocListItem, error) {
|
||||
out := make([]LibraryDocListItem, 0, len(details))
|
||||
for _, d := range details {
|
||||
out = append(out, LibraryDocListItem{
|
||||
ID: d.ID, Slug: d.Slug, Title: d.Title, CoverURL: d.CoverURL,
|
||||
SortOrder: d.SortOrder, FileCount: len(d.Files), Files: d.Files,
|
||||
ID: d.ID, Slug: d.Slug, Title: d.Title, Author: d.Author, Description: d.Description,
|
||||
CoverURL: d.CoverURL, SortOrder: d.SortOrder, FileCount: len(d.Files), Files: d.Files,
|
||||
Creator: d.Creator,
|
||||
CreatedAt: d.CreatedAt, UpdatedAt: d.UpdatedAt,
|
||||
})
|
||||
}
|
||||
@@ -364,6 +510,8 @@ func (s *LibraryService) GetPublishedBySlug(slug string) (*LibraryDocDetail, err
|
||||
if err := s.db.Where("slug = ? AND published = ?", slug, true).First(&d).Error; err != nil {
|
||||
return nil, ErrLibraryNotFound
|
||||
}
|
||||
// 懒回填:有封面但未存尺寸时当场测量并写回(首次访问后即稳定,消除横竖版探测闪烁)
|
||||
s.ensureCoverDimensions(&d)
|
||||
out := s.attachFiles([]model.LibraryDoc{d})
|
||||
return &out[0], nil
|
||||
}
|
||||
|
||||
369
backend/service/library_export.go
Normal file
@@ -0,0 +1,369 @@
|
||||
package service
|
||||
|
||||
// 书库导出:单本 / 全部条目打包为 ZIP(JSON 清单 + 章节正文 + 附件原文件 + 本地封面),
|
||||
// 用于迁移与备份。清单自描述(format + format_version),为将来的导入功能预留。
|
||||
//
|
||||
// 单本 ZIP 布局:
|
||||
//
|
||||
// book.json 书籍清单(元信息 / 章节树 / 附件清单,路径均相对本目录)
|
||||
// cover.<ext> 本地封面(外链封面不内嵌,仅保留 cover_url)
|
||||
// files/<stored-name> 附件原文件
|
||||
//
|
||||
// 全库 ZIP 布局:
|
||||
//
|
||||
// library.json 索引(每本书的目录位置)
|
||||
// docs/<slug>/book.json 各书清单
|
||||
// docs/<slug>/cover.<ext>
|
||||
// docs/<slug>/files/<stored-name>
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
)
|
||||
|
||||
const (
|
||||
libraryExportFormat = "jiang13-library" // 全库包
|
||||
libraryExportBookFormat = "jiang13-library-book" // 单本书包
|
||||
libraryExportVersion = 1
|
||||
)
|
||||
|
||||
// 可内嵌进导出包的本地封面扩展名(与上传层支持的图片格式保持一致)
|
||||
var libraryExportCoverExts = map[string]struct{}{
|
||||
"jpg": {}, "jpeg": {}, "png": {}, "gif": {}, "webp": {},
|
||||
}
|
||||
|
||||
// libraryExportFile 附件清单条目
|
||||
type libraryExportFile struct {
|
||||
Name string `json:"name"` // 原始文件名
|
||||
Stored string `json:"stored,omitempty"` // ZIP 内相对路径(磁盘缺失时为空)
|
||||
Ext string `json:"ext"`
|
||||
MIME string `json:"mime"`
|
||||
Size int `json:"size"`
|
||||
DownloadCount int `json:"download_count"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
Missing bool `json:"missing,omitempty"` // 数据库有记录但磁盘文件已丢失
|
||||
}
|
||||
|
||||
// libraryExportSection 章节清单条目(两级树:ParentKey 指向章的 Key)
|
||||
type libraryExportSection struct {
|
||||
Key string `json:"key"`
|
||||
ParentKey string `json:"parent_key,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// libraryExportBook 单本书的完整清单
|
||||
type libraryExportBook struct {
|
||||
ID uint `json:"id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Author string `json:"author"`
|
||||
Description string `json:"description"`
|
||||
CoverURL string `json:"cover_url"`
|
||||
CoverFile string `json:"cover_file,omitempty"` // 相对本书目录的内嵌封面路径
|
||||
CoverWidth int `json:"cover_width"`
|
||||
CoverHeight int `json:"cover_height"`
|
||||
Published bool `json:"published"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
EntriesAuto bool `json:"entries_auto"`
|
||||
|
||||
Files []libraryExportFile `json:"files"`
|
||||
Sections []libraryExportSection `json:"sections"`
|
||||
}
|
||||
|
||||
// libraryExportIndexEntry 全库索引中的单本概要
|
||||
type libraryExportIndexEntry struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Dir string `json:"dir"` // 相对 ZIP 根的目录
|
||||
FileCount int `json:"file_count"`
|
||||
SectionCount int `json:"section_count"`
|
||||
}
|
||||
|
||||
// libraryExportManifest ZIP 根清单:单本包用 Doc,全库包用 Docs 索引
|
||||
type libraryExportManifest struct {
|
||||
Format string `json:"format"`
|
||||
FormatVersion int `json:"format_version"`
|
||||
ExportedAt string `json:"exported_at"`
|
||||
Doc *libraryExportBook `json:"doc,omitempty"`
|
||||
Docs []libraryExportIndexEntry `json:"docs,omitempty"`
|
||||
}
|
||||
|
||||
// preparedFile 已打开、待流式拷入 ZIP 的附件
|
||||
type preparedFile struct {
|
||||
zipPath string
|
||||
reader *os.File
|
||||
}
|
||||
|
||||
// preparedBook 一本书的导出准备结果(清单 + 已打开的文件句柄)
|
||||
type preparedBook struct {
|
||||
meta libraryExportBook
|
||||
dir string // ZIP 内目录前缀(单本包为空串 = 根目录)
|
||||
coverPath string // ZIP 内封面路径(空 = 不内嵌)
|
||||
coverReader *os.File
|
||||
files []preparedFile // 仅磁盘存在的附件
|
||||
}
|
||||
|
||||
func (b *preparedBook) closeReaders() {
|
||||
if b.coverReader != nil {
|
||||
_ = b.coverReader.Close()
|
||||
}
|
||||
for i := range b.files {
|
||||
_ = b.files[i].reader.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// LibraryExport 已完成装载、可直接流式写出的导出包
|
||||
type LibraryExport struct {
|
||||
Filename string
|
||||
full bool
|
||||
exportedAt time.Time
|
||||
books []preparedBook
|
||||
}
|
||||
|
||||
// Close 释放导出过程中打开的全部文件句柄
|
||||
func (e *LibraryExport) Close() {
|
||||
for i := range e.books {
|
||||
e.books[i].closeReaders()
|
||||
}
|
||||
}
|
||||
|
||||
// BuildBookExport 装载单本书导出(不存在返回 ErrLibraryNotFound)。
|
||||
// 所有失败均发生在写出之前,handler 可安全返回 JSON 错误。
|
||||
func (s *LibraryService) BuildBookExport(id uint) (*LibraryExport, error) {
|
||||
d, err := s.Get(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := s.prepareBook(d, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
name := d.Slug
|
||||
if name == "" {
|
||||
name = "book"
|
||||
}
|
||||
return &LibraryExport{
|
||||
Filename: name + ".zip",
|
||||
full: false,
|
||||
exportedAt: time.Now(),
|
||||
books: []preparedBook{*b},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// BuildAllExport 装载全库导出(仅在用条目,按 sort_order / id 排序)
|
||||
func (s *LibraryService) BuildAllExport() (*LibraryExport, error) {
|
||||
var docs []model.LibraryDoc
|
||||
if err := s.db.Order("sort_order ASC, id ASC").Find(&docs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
details := s.attachFiles(docs)
|
||||
exp := &LibraryExport{
|
||||
Filename: "jiang13-library-" + time.Now().Format("20060102-150405") + ".zip",
|
||||
full: true,
|
||||
exportedAt: time.Now(),
|
||||
books: make([]preparedBook, 0, len(details)),
|
||||
}
|
||||
for i := range details {
|
||||
// slug 受 [a-z0-9-] 约束,拼接 ZIP 路径无穿越风险;防御性兜底
|
||||
dir := "docs/" + details[i].Slug + "/"
|
||||
if strings.Contains(details[i].Slug, "..") || strings.ContainsAny(details[i].Slug, `/\`) {
|
||||
exp.Close()
|
||||
return nil, errors.New("条目 slug 含非法字符,无法导出")
|
||||
}
|
||||
b, err := s.prepareBook(&details[i], dir)
|
||||
if err != nil {
|
||||
exp.Close()
|
||||
return nil, err
|
||||
}
|
||||
exp.books = append(exp.books, *b)
|
||||
}
|
||||
return exp, nil
|
||||
}
|
||||
|
||||
// prepareBook 组装单本清单并打开全部待打包文件(dir 为 ZIP 内目录前缀)
|
||||
func (s *LibraryService) prepareBook(d *LibraryDocDetail, dir string) (*preparedBook, error) {
|
||||
b := &preparedBook{dir: dir}
|
||||
b.meta = libraryExportBook{
|
||||
ID: d.ID,
|
||||
CreatedAt: d.CreatedAt.UTC().Format(time.RFC3339),
|
||||
UpdatedAt: d.UpdatedAt.UTC().Format(time.RFC3339),
|
||||
Slug: d.Slug,
|
||||
Title: d.Title,
|
||||
Author: d.Author,
|
||||
Description: d.Description,
|
||||
CoverURL: d.CoverURL,
|
||||
CoverWidth: d.CoverWidth,
|
||||
CoverHeight: d.CoverHeight,
|
||||
Published: d.Published,
|
||||
SortOrder: d.SortOrder,
|
||||
EntriesAuto: d.EntriesAuto,
|
||||
Files: make([]libraryExportFile, 0, len(d.Files)),
|
||||
Sections: make([]libraryExportSection, 0, len(d.Sections)),
|
||||
}
|
||||
|
||||
// 章节:按数组序号发 Key,ParentKey 引用父章 Key(attachFiles 已按 sort_order, id 排序)
|
||||
keyByID := make(map[uint]string, len(d.Sections))
|
||||
for i, sec := range d.Sections {
|
||||
keyByID[sec.ID] = "s" + strconv.Itoa(i)
|
||||
}
|
||||
for _, sec := range d.Sections {
|
||||
m := libraryExportSection{
|
||||
Key: keyByID[sec.ID],
|
||||
Title: sec.Title,
|
||||
Content: sec.Content,
|
||||
SortOrder: sec.SortOrder,
|
||||
}
|
||||
if sec.ParentID != nil {
|
||||
m.ParentKey = keyByID[*sec.ParentID]
|
||||
}
|
||||
b.meta.Sections = append(b.meta.Sections, m)
|
||||
}
|
||||
|
||||
// 附件:数据库清单始终保留;磁盘文件存在才打开并记录 ZIP 路径
|
||||
for _, f := range d.Files {
|
||||
m := libraryExportFile{
|
||||
Name: f.Name,
|
||||
Ext: f.Ext,
|
||||
MIME: f.MIME,
|
||||
Size: f.Size,
|
||||
DownloadCount: f.DownloadCount,
|
||||
SortOrder: f.SortOrder,
|
||||
}
|
||||
full := filepath.Join(s.dir, f.StoredName)
|
||||
if r, err := os.Open(full); err == nil {
|
||||
m.Stored = "files/" + f.StoredName
|
||||
b.files = append(b.files, preparedFile{zipPath: dir + m.Stored, reader: r})
|
||||
} else {
|
||||
m.Missing = true
|
||||
}
|
||||
b.meta.Files = append(b.meta.Files, m)
|
||||
}
|
||||
|
||||
// 本地封面(/uploads/...):能解析到磁盘文件则内嵌;外链或缺目录时仅保留 URL
|
||||
if rel, ok := s.resolveCoverPath(d.CoverURL); ok {
|
||||
if ext := coverExtOf(d.CoverURL); ext != "" {
|
||||
if r, err := os.Open(rel); err == nil {
|
||||
b.coverReader = r
|
||||
b.coverPath = dir + "cover." + ext
|
||||
b.meta.CoverFile = "cover." + ext
|
||||
}
|
||||
}
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// WriteZip 流式写出 ZIP。调用后文件句柄随之释放;中途的 IO 错误已无法改变 HTTP 状态。
|
||||
func (e *LibraryExport) WriteZip(w io.Writer) error {
|
||||
defer e.Close()
|
||||
zw := zip.NewWriter(w)
|
||||
|
||||
index := make([]libraryExportIndexEntry, 0, len(e.books))
|
||||
for i := range e.books {
|
||||
b := &e.books[i]
|
||||
// 全库包每本书在自己的目录内写 book.json;单本包的根清单即 book.json,在循环外写
|
||||
if e.full {
|
||||
if err := writeZipJSON(zw, b.dir+"book.json", b.meta); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if b.coverReader != nil {
|
||||
if err := writeZipFile(zw, b.coverPath, b.coverReader); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for j := range b.files {
|
||||
if err := writeZipFile(zw, b.files[j].zipPath, b.files[j].reader); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
index = append(index, libraryExportIndexEntry{
|
||||
Slug: b.meta.Slug,
|
||||
Title: b.meta.Title,
|
||||
Dir: b.dir,
|
||||
FileCount: len(b.meta.Files),
|
||||
SectionCount: len(b.meta.Sections),
|
||||
})
|
||||
}
|
||||
|
||||
// 单本包根清单为 book.json;全库包根清单为 library.json(各书清单在其目录内)
|
||||
if e.full {
|
||||
root := libraryExportManifest{
|
||||
Format: libraryExportFormat,
|
||||
FormatVersion: libraryExportVersion,
|
||||
ExportedAt: e.exportedAt.UTC().Format(time.RFC3339),
|
||||
Docs: index,
|
||||
}
|
||||
if err := writeZipJSON(zw, "library.json", root); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
root := libraryExportManifest{
|
||||
Format: libraryExportBookFormat,
|
||||
FormatVersion: libraryExportVersion,
|
||||
ExportedAt: e.exportedAt.UTC().Format(time.RFC3339),
|
||||
Doc: &e.books[0].meta,
|
||||
}
|
||||
if err := writeZipJSON(zw, "book.json", root); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return zw.Close()
|
||||
}
|
||||
|
||||
// coverExtOf 从 /uploads/xx.jpg 形式的封面 URL 提取受支持的图片扩展名
|
||||
func coverExtOf(coverURL string) string {
|
||||
u := strings.TrimSpace(coverURL)
|
||||
if i := strings.IndexByte(u, '?'); i >= 0 {
|
||||
u = u[:i]
|
||||
}
|
||||
ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(u), "."))
|
||||
if _, ok := libraryExportCoverExts[ext]; !ok {
|
||||
return ""
|
||||
}
|
||||
return ext
|
||||
}
|
||||
|
||||
// writeZipJSON 写入一个 DEFLATE 压缩的 UTF-8 JSON 条目(关闭 HTML 转义、缩进可读)
|
||||
func writeZipJSON(zw *zip.Writer, name string, v any) error {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return err
|
||||
}
|
||||
hdr := &zip.FileHeader{Name: name, Method: zip.Deflate}
|
||||
hdr.SetMode(0o644)
|
||||
f, err := zw.CreateHeader(hdr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.Write(buf.Bytes())
|
||||
return err
|
||||
}
|
||||
|
||||
// writeZipFile 以 STORE 方式原样写入二进制附件(多为已压缩格式,重复 deflate 仅耗 CPU)
|
||||
func writeZipFile(zw *zip.Writer, name string, r io.Reader) error {
|
||||
hdr := &zip.FileHeader{Name: name, Method: zip.Store}
|
||||
hdr.SetMode(0o644)
|
||||
f, err := zw.CreateHeader(hdr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(f, r)
|
||||
return err
|
||||
}
|
||||
199
backend/service/library_export_test.go
Normal file
@@ -0,0 +1,199 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// readZipEntry 读取 ZIP 内指定名称的文件内容(不存在返回 nil, false)
|
||||
func readZipEntry(t *testing.T, zr *zip.Reader, name string) ([]byte, bool) {
|
||||
t.Helper()
|
||||
for _, f := range zr.File {
|
||||
if f.Name == name {
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
t.Fatalf("open zip entry %s: %v", name, err)
|
||||
}
|
||||
defer rc.Close()
|
||||
data, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatalf("read zip entry %s: %v", name, err)
|
||||
}
|
||||
return data, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func buildExportZip(t *testing.T, exp *LibraryExport) *zip.Reader {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := exp.WriteZip(&buf); err != nil {
|
||||
t.Fatalf("write zip: %v", err)
|
||||
}
|
||||
zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
|
||||
if err != nil {
|
||||
t.Fatalf("read exported zip: %v", err)
|
||||
}
|
||||
return zr
|
||||
}
|
||||
|
||||
// seedBookForExport 造一本含章节(章 + 小节)、附件与本地封面的书籍
|
||||
func seedBookForExport(t *testing.T, s *LibraryService, uploads string) (docID uint, storedName string) {
|
||||
t.Helper()
|
||||
pub := true
|
||||
doc, err := s.Create(&LibraryInput{Slug: "dao-jia", Title: "道家研究", Author: "老子", Description: "# 介绍"})
|
||||
if err != nil {
|
||||
t.Fatalf("create doc: %v", err)
|
||||
}
|
||||
|
||||
coverDir := filepath.Join(uploads, "images")
|
||||
if err := os.MkdirAll(coverDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir uploads: %v", err)
|
||||
}
|
||||
coverBytes := encodeJPEGBytes(t, 120, 160)
|
||||
if err := os.WriteFile(filepath.Join(coverDir, "cover.jpg"), coverBytes, 0o644); err != nil {
|
||||
t.Fatalf("write cover: %v", err)
|
||||
}
|
||||
if _, err := s.Update(doc.ID, &LibraryInput{
|
||||
Slug: "dao-jia", Title: "道家研究", Author: "老子", Description: "# 介绍",
|
||||
CoverURL: "/uploads/images/cover.jpg", CoverWidth: 120, CoverHeight: 160,
|
||||
Published: &pub,
|
||||
}); err != nil {
|
||||
t.Fatalf("update cover: %v", err)
|
||||
}
|
||||
|
||||
chapter, err := s.CreateSection(doc.ID, &SectionInput{Title: "第一章", Content: "章正文"})
|
||||
if err != nil {
|
||||
t.Fatalf("create chapter: %v", err)
|
||||
}
|
||||
if _, err := s.CreateSection(doc.ID, &SectionInput{
|
||||
ParentID: &chapter.ID, Title: "小节", Content: "小节正文",
|
||||
}); err != nil {
|
||||
t.Fatalf("create section: %v", err)
|
||||
}
|
||||
|
||||
f, err := s.AddFile(doc.ID, 1, "manual.epub", bytes.NewReader([]byte("EPUB-FILE-BYTES")))
|
||||
if err != nil {
|
||||
t.Fatalf("add file: %v", err)
|
||||
}
|
||||
return doc.ID, f.StoredName
|
||||
}
|
||||
|
||||
func TestLibraryExportBook(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
uploads := t.TempDir()
|
||||
s.WithUploadsDir(uploads)
|
||||
docID, storedName := seedBookForExport(t, s, uploads)
|
||||
|
||||
exp, err := s.BuildBookExport(docID)
|
||||
if err != nil {
|
||||
t.Fatalf("build export: %v", err)
|
||||
}
|
||||
defer exp.Close()
|
||||
if exp.Filename != "dao-jia.zip" {
|
||||
t.Fatalf("filename = %q, want dao-jia.zip", exp.Filename)
|
||||
}
|
||||
zr := buildExportZip(t, exp)
|
||||
|
||||
raw, ok := readZipEntry(t, zr, "book.json")
|
||||
if !ok {
|
||||
t.Fatal("缺少 book.json")
|
||||
}
|
||||
var manifest libraryExportManifest
|
||||
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||
t.Fatalf("parse book.json: %v", err)
|
||||
}
|
||||
if manifest.Format != libraryExportBookFormat || manifest.FormatVersion != libraryExportVersion {
|
||||
t.Fatalf("清单格式异常: %s v%d", manifest.Format, manifest.FormatVersion)
|
||||
}
|
||||
b := manifest.Doc
|
||||
if b == nil {
|
||||
t.Fatal("book.json 缺少 doc")
|
||||
}
|
||||
if b.Title != "道家研究" || b.Slug != "dao-jia" || b.Author != "老子" || !b.Published {
|
||||
t.Fatalf("元信息导出不正确: %+v", b)
|
||||
}
|
||||
if b.CoverFile != "cover.jpg" || b.CoverWidth != 120 || b.CoverHeight != 160 {
|
||||
t.Fatalf("封面信息导出不正确: %+v", b)
|
||||
}
|
||||
if len(b.Sections) != 2 || b.Sections[0].Key != "s0" || b.Sections[1].ParentKey != "s0" {
|
||||
t.Fatalf("章节树导出不正确: %+v", b.Sections)
|
||||
}
|
||||
if len(b.Files) != 1 || b.Files[0].Stored != "files/"+storedName || b.Files[0].Missing {
|
||||
t.Fatalf("附件清单导出不正确: %+v", b.Files)
|
||||
}
|
||||
|
||||
if data, ok := readZipEntry(t, zr, "files/"+storedName); !ok || string(data) != "EPUB-FILE-BYTES" {
|
||||
t.Fatalf("附件内容导出不正确(ok=%v)", ok)
|
||||
}
|
||||
if data, ok := readZipEntry(t, zr, "cover.jpg"); !ok || !bytes.HasPrefix(data, []byte{0xff, 0xd8, 0xff}) {
|
||||
t.Fatalf("封面内容导出不正确(ok=%v)", ok)
|
||||
}
|
||||
// 单本包不应出现全库索引
|
||||
if _, ok := readZipEntry(t, zr, "library.json"); ok {
|
||||
t.Fatal("单本包不应包含 library.json")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryExportAll(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
uploads := t.TempDir()
|
||||
s.WithUploadsDir(uploads)
|
||||
docID, storedName := seedBookForExport(t, s, uploads)
|
||||
_ = docID
|
||||
|
||||
exp, err := s.BuildAllExport()
|
||||
if err != nil {
|
||||
t.Fatalf("build all export: %v", err)
|
||||
}
|
||||
defer exp.Close()
|
||||
zr := buildExportZip(t, exp)
|
||||
|
||||
raw, ok := readZipEntry(t, zr, "library.json")
|
||||
if !ok {
|
||||
t.Fatal("缺少 library.json")
|
||||
}
|
||||
var manifest libraryExportManifest
|
||||
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||
t.Fatalf("parse library.json: %v", err)
|
||||
}
|
||||
if manifest.Format != libraryExportFormat || len(manifest.Docs) != 1 {
|
||||
t.Fatalf("全库索引异常: %+v", manifest)
|
||||
}
|
||||
idx := manifest.Docs[0]
|
||||
if idx.Dir != "docs/dao-jia/" || idx.FileCount != 1 || idx.SectionCount != 2 {
|
||||
t.Fatalf("索引条目异常: %+v", idx)
|
||||
}
|
||||
|
||||
bookRaw, ok := readZipEntry(t, zr, "docs/dao-jia/book.json")
|
||||
if !ok {
|
||||
t.Fatal("缺少 docs/dao-jia/book.json")
|
||||
}
|
||||
var book libraryExportBook
|
||||
if err := json.Unmarshal(bookRaw, &book); err != nil {
|
||||
t.Fatalf("parse nested book.json: %v", err)
|
||||
}
|
||||
if book.Slug != "dao-jia" || book.CoverFile != "cover.jpg" {
|
||||
t.Fatalf("嵌套书籍清单异常: %+v", book)
|
||||
}
|
||||
if _, ok := readZipEntry(t, zr, "docs/dao-jia/files/"+storedName); !ok {
|
||||
t.Fatal("缺少嵌套附件")
|
||||
}
|
||||
if _, ok := readZipEntry(t, zr, "docs/dao-jia/cover.jpg"); !ok {
|
||||
t.Fatal("缺少嵌套封面")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryExportMissingDoc(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
if _, err := s.BuildBookExport(999); !errors.Is(err, ErrLibraryNotFound) {
|
||||
t.Fatalf("不存在的条目应返回 ErrLibraryNotFound,got %v", err)
|
||||
}
|
||||
}
|
||||
631
backend/service/library_import.go
Normal file
@@ -0,0 +1,631 @@
|
||||
package service
|
||||
|
||||
// 书库导入恢复:解析导出 ZIP(见 library_export.go),在本站重建书籍。
|
||||
//
|
||||
// - 单本包(根 book.json,format=jiang13-library-book)与全库包(library.json 索引)
|
||||
// - mode=create(默认):同 slug 在用条目冲突时跳过该书;软删占用同样拒绝(释放后再来)
|
||||
// - mode=overwrite:覆盖同 slug 在用条目(章节/附件整体替换,元信息按包恢复)
|
||||
// - 附件复用 AddFile(扩展名白名单/大小/20 个上限/随机落盘),磁盘名重新生成但保留下载计数
|
||||
// - 内嵌封面按魔数校验后随机名落盘 uploads/images;外链封面仅保留 URL
|
||||
// - 逐本独立处理:单本书失败不影响包内其他书,结果以报告返回(包本身非法才整体报错)
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// LibraryImportMaxBytes 导入 ZIP 上传上限(超出由 handler 提前拦截)
|
||||
const LibraryImportMaxBytes = 512 << 20
|
||||
|
||||
const (
|
||||
LibraryImportModeCreate = "create" // 冲突跳过
|
||||
LibraryImportModeOverwrite = "overwrite" // 冲突覆盖
|
||||
)
|
||||
|
||||
// 失败原因(前端据此区分冲突,可提示覆盖重导)
|
||||
const (
|
||||
libraryImportReasonConflict = "conflict" // slug 被在用条目占用(create 模式)
|
||||
libraryImportReasonDeleted = "deleted" // slug 被已软删条目占用
|
||||
libraryImportReasonInvalid = "invalid" // 清单数据非法
|
||||
libraryImportReasonFailed = "failed" // 落盘/写库失败
|
||||
)
|
||||
|
||||
var (
|
||||
ErrLibraryImportBadZip = errors.New("无法读取导入文件,请上传书库导出的 ZIP 备份包")
|
||||
ErrLibraryImportFormat = errors.New("不是有效的书库导出包:缺少清单文件或清单已损坏")
|
||||
ErrLibraryImportVer = errors.New("导出版本不受支持")
|
||||
ErrLibraryImportEmpty = errors.New("备份包内没有可导入的书籍")
|
||||
ErrLibraryImportMode = errors.New("无效的导入模式")
|
||||
)
|
||||
|
||||
// LibraryImportItem 成功导入的单本结果
|
||||
type LibraryImportItem struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Action string `json:"action"` // created / overwritten
|
||||
Sections int `json:"sections"`
|
||||
Files int `json:"files"`
|
||||
}
|
||||
|
||||
// LibraryImportFailure 单本书失败明细
|
||||
type LibraryImportFailure struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Reason string `json:"reason"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
// LibraryImportReport 导入报告
|
||||
type LibraryImportReport struct {
|
||||
Mode string `json:"mode"`
|
||||
Total int `json:"total"`
|
||||
Imported []LibraryImportItem `json:"imported"`
|
||||
Failed []LibraryImportFailure `json:"failed"`
|
||||
}
|
||||
|
||||
// bookImportPlan 单本书的导入计划(清单 + ZIP 内目录前缀)
|
||||
type bookImportPlan struct {
|
||||
book libraryExportBook
|
||||
dir string
|
||||
}
|
||||
|
||||
// plannedSection 重建后的章节(保留原始 key 用于两级映射;sort 为同层级序号)
|
||||
type plannedSection struct {
|
||||
key string
|
||||
parentKey string
|
||||
title string
|
||||
content string
|
||||
sort int
|
||||
}
|
||||
|
||||
// ImportLibraryZip 从导出 ZIP 恢复书籍。zipPath 为已落盘的临时文件路径。
|
||||
func (s *LibraryService) ImportLibraryZip(zipPath, mode string, userID uint) (*LibraryImportReport, error) {
|
||||
if mode != LibraryImportModeCreate && mode != LibraryImportModeOverwrite {
|
||||
return nil, ErrLibraryImportMode
|
||||
}
|
||||
zr, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return nil, ErrLibraryImportBadZip
|
||||
}
|
||||
defer zr.Close()
|
||||
|
||||
entries := make(map[string]*zip.File, len(zr.File))
|
||||
for _, f := range zr.File {
|
||||
if f.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
entries[strings.ReplaceAll(f.Name, "\\", "/")] = f // 正常包无重名
|
||||
}
|
||||
|
||||
plans, err := parseImportPlans(entries)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(plans) == 0 {
|
||||
return nil, ErrLibraryImportEmpty
|
||||
}
|
||||
|
||||
rep := &LibraryImportReport{
|
||||
Mode: mode,
|
||||
Total: len(plans),
|
||||
Imported: []LibraryImportItem{},
|
||||
Failed: []LibraryImportFailure{},
|
||||
}
|
||||
imp := &bookImporter{s: s, entries: entries, userID: userID}
|
||||
for _, p := range plans {
|
||||
item, fail := imp.run(p, mode)
|
||||
if fail != nil {
|
||||
rep.Failed = append(rep.Failed, *fail)
|
||||
} else {
|
||||
rep.Imported = append(rep.Imported, *item)
|
||||
}
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
|
||||
// parseImportPlans 识别单本/全库包并解析书籍清单(不读正文/附件)
|
||||
func parseImportPlans(entries map[string]*zip.File) ([]bookImportPlan, error) {
|
||||
if rootRaw, ok := entries["library.json"]; ok {
|
||||
var root libraryExportManifest
|
||||
if err := readZipJSON(rootRaw, &root); err != nil {
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
if root.Format != libraryExportFormat || root.FormatVersion != libraryExportVersion {
|
||||
return nil, ErrLibraryImportVer
|
||||
}
|
||||
plans := make([]bookImportPlan, 0, len(root.Docs))
|
||||
for _, d := range root.Docs {
|
||||
dir := strings.ReplaceAll(d.Dir, "\\", "/")
|
||||
if !safeImportDir(dir) {
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
raw, ok := entries[path.Clean(dir)+"/book.json"]
|
||||
if !ok {
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
var b libraryExportBook
|
||||
if err := readZipJSON(raw, &b); err != nil {
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
plans = append(plans, bookImportPlan{book: b, dir: dir})
|
||||
}
|
||||
return plans, nil
|
||||
}
|
||||
if rootRaw, ok := entries["book.json"]; ok {
|
||||
var root libraryExportManifest
|
||||
if err := readZipJSON(rootRaw, &root); err != nil {
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
if root.Format != libraryExportBookFormat || root.FormatVersion != libraryExportVersion || root.Doc == nil {
|
||||
return nil, ErrLibraryImportVer
|
||||
}
|
||||
return []bookImportPlan{{book: *root.Doc, dir: ""}}, nil
|
||||
}
|
||||
return nil, ErrLibraryImportFormat
|
||||
}
|
||||
|
||||
// safeImportDir 全库包内目录必须是 docs/<slug>/ 形态(slug 与条目同规则)
|
||||
func safeImportDir(dir string) bool {
|
||||
if dir == "" || !strings.HasPrefix(dir, "docs/") || !strings.HasSuffix(dir, "/") {
|
||||
return false
|
||||
}
|
||||
slug := strings.TrimSuffix(strings.TrimPrefix(dir, "docs/"), "/")
|
||||
if strings.Contains(slug, "/") || strings.Contains(slug, "..") {
|
||||
return false
|
||||
}
|
||||
return sitePageSlugRe.MatchString(slug)
|
||||
}
|
||||
|
||||
// bookImporter 携带一次批量导入的共享上下文
|
||||
type bookImporter struct {
|
||||
s *LibraryService
|
||||
entries map[string]*zip.File
|
||||
userID uint
|
||||
}
|
||||
|
||||
func (imp *bookImporter) fail(p bookImportPlan, reason, msg string) *LibraryImportFailure {
|
||||
return &LibraryImportFailure{Slug: p.book.Slug, Title: p.book.Title, Reason: reason, Error: msg}
|
||||
}
|
||||
|
||||
// run 导入单本书;返回 item 或 failure(二者互斥)
|
||||
func (imp *bookImporter) run(p bookImportPlan, mode string) (*LibraryImportItem, *LibraryImportFailure) {
|
||||
b := p.book
|
||||
|
||||
in, err := buildImportInput(&b)
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonInvalid, err.Error())
|
||||
}
|
||||
sections, err := buildImportSections(&b)
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonInvalid, err.Error())
|
||||
}
|
||||
if err := imp.checkPlannedFiles(p); err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonInvalid, err.Error())
|
||||
}
|
||||
coverEntry, err := imp.planCover(p)
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonInvalid, err.Error())
|
||||
}
|
||||
|
||||
active, deleted, err := imp.s.slugTaken(b.Slug, 0)
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "查询条目失败")
|
||||
}
|
||||
|
||||
var docID uint
|
||||
action := "created"
|
||||
var oldFiles []model.LibraryFile // overwrite 时待删磁盘附件
|
||||
var oldCoverDisk string // overwrite 时待删旧封面(仅本地 /uploads)
|
||||
backfillCreator := false // overwrite 且原条目无创建者时补记导入操作人
|
||||
switch {
|
||||
case active && mode != LibraryImportModeOverwrite:
|
||||
return nil, imp.fail(p, libraryImportReasonConflict, "slug 已被在用条目占用:"+b.Slug)
|
||||
case active:
|
||||
var existing model.LibraryDoc
|
||||
if err := imp.s.db.Where("slug = ?", b.Slug).First(&existing).Error; err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "读取原条目失败")
|
||||
}
|
||||
docID = existing.ID
|
||||
// 跨站恢复不导出创建者:原条目无创建者时把本次导入操作人补为创建者
|
||||
backfillCreator = existing.CreatorID == 0
|
||||
_ = imp.s.db.Where("doc_id = ?", docID).Find(&oldFiles).Error
|
||||
if disk, ok := imp.s.resolveCoverPath(existing.CoverURL); ok {
|
||||
oldCoverDisk = disk
|
||||
}
|
||||
action = "overwritten"
|
||||
case deleted:
|
||||
return nil, imp.fail(p, libraryImportReasonDeleted,
|
||||
"该地址被已删除条目占用,请先在书库管理中彻底删除后再导入:"+b.Slug)
|
||||
}
|
||||
|
||||
// 内嵌封面先落盘(URL 在事务前确定;create 失败时随条目回滚删除)
|
||||
coverDisk := ""
|
||||
if coverEntry != nil {
|
||||
url, w, h, disk, ferr := imp.materializeCover(coverEntry)
|
||||
if ferr != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "封面恢复失败:"+ferr.Error())
|
||||
}
|
||||
in.CoverURL, in.CoverWidth, in.CoverHeight, coverDisk = url, w, h, disk
|
||||
}
|
||||
// 无内嵌封面时保留清单原值(外链或原站 /uploads URL)与尺寸
|
||||
|
||||
txErr := imp.s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if action == "created" {
|
||||
d := &model.LibraryDoc{Published: false, SortOrder: 0, CreatorID: imp.userID}
|
||||
in.applyTo(d)
|
||||
if err := tx.Select(libraryDocWriteFields).Create(d).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
docID = d.ID
|
||||
} else {
|
||||
var d model.LibraryDoc
|
||||
if err := tx.First(&d, docID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
in.applyTo(&d)
|
||||
updates := map[string]interface{}{
|
||||
"slug": d.Slug,
|
||||
"title": d.Title,
|
||||
"author": d.Author,
|
||||
"description": d.Description,
|
||||
"cover_url": d.CoverURL,
|
||||
"cover_width": d.CoverWidth,
|
||||
"cover_height": d.CoverHeight,
|
||||
"published": d.Published,
|
||||
"sort_order": d.SortOrder,
|
||||
"entries_auto": d.EntriesAuto,
|
||||
}
|
||||
if backfillCreator {
|
||||
updates["creator_id"] = imp.userID
|
||||
}
|
||||
if err := tx.Model(&model.LibraryDoc{}).Where("id = ?", d.ID).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Unscoped().Where("doc_id = ?", docID).Delete(&model.LibrarySection{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Unscoped().Where("doc_id = ?", docID).Delete(&model.LibraryFile{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return imp.createSections(tx, docID, sections)
|
||||
})
|
||||
if txErr != nil {
|
||||
if action == "created" && coverDisk != "" {
|
||||
_ = os.Remove(coverDisk)
|
||||
}
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "写入数据库失败:"+txErr.Error())
|
||||
}
|
||||
|
||||
// overwrite 事务成功后清理旧附件与旧封面磁盘文件(失败不影响结果)
|
||||
for i := range oldFiles {
|
||||
_ = os.Remove(imp.s.FilePath(&oldFiles[i]))
|
||||
}
|
||||
if oldCoverDisk != "" && oldCoverDisk != coverDisk {
|
||||
_ = os.Remove(oldCoverDisk)
|
||||
}
|
||||
|
||||
// 附件落盘。create 阶段失败需硬删新建条目以释放 slug;overwrite 仅报告失败
|
||||
added := 0
|
||||
var newFiles []model.LibraryFile
|
||||
for _, mf := range b.Files {
|
||||
if mf.Missing || mf.Stored == "" {
|
||||
continue // 导出时磁盘已丢失的附件:清单保留记录但无文件可恢复
|
||||
}
|
||||
f, fail := imp.addPlannedFile(p, docID, mf)
|
||||
if fail != nil {
|
||||
if action == "created" {
|
||||
imp.rollbackCreated(docID, newFiles, coverDisk)
|
||||
}
|
||||
return nil, fail
|
||||
}
|
||||
newFiles = append(newFiles, *f)
|
||||
added++
|
||||
}
|
||||
|
||||
return &LibraryImportItem{
|
||||
Slug: b.Slug,
|
||||
Title: b.Title,
|
||||
Action: action,
|
||||
Sections: len(sections),
|
||||
Files: added,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ---------- 清单解析与预检 ----------
|
||||
|
||||
func buildImportInput(b *libraryExportBook) (*LibraryInput, error) {
|
||||
pub, sortOrder, entriesAuto := b.Published, b.SortOrder, b.EntriesAuto
|
||||
in := &LibraryInput{
|
||||
Slug: b.Slug,
|
||||
Title: b.Title,
|
||||
Author: b.Author,
|
||||
Description: b.Description,
|
||||
CoverURL: b.CoverURL,
|
||||
CoverWidth: b.CoverWidth,
|
||||
CoverHeight: b.CoverHeight,
|
||||
Published: &pub,
|
||||
SortOrder: &sortOrder,
|
||||
EntriesAuto: &entriesAuto,
|
||||
}
|
||||
if err := in.normalize(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
|
||||
// buildImportSections 两轮解析:先章(编号)后节(按父分组编号),校验标题/正文/父引用
|
||||
func buildImportSections(b *libraryExportBook) ([]plannedSection, error) {
|
||||
if len(b.Sections) > MaxSectionsPerDoc {
|
||||
return nil, errors.New("章节数量超过上限(最多 200)")
|
||||
}
|
||||
keySeen := map[string]bool{}
|
||||
out := make([]plannedSection, 0, len(b.Sections))
|
||||
|
||||
chapterSort := map[string]int{}
|
||||
order := 0
|
||||
for _, sec := range b.Sections {
|
||||
if sec.ParentKey != "" {
|
||||
continue
|
||||
}
|
||||
title := strings.TrimSpace(sec.Title)
|
||||
if title == "" {
|
||||
return nil, errors.New("存在标题为空的章节")
|
||||
}
|
||||
if err := validateSectionText(title, sec.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if keySeen[sec.Key] {
|
||||
return nil, errors.New("章节标识重复:" + sec.Key)
|
||||
}
|
||||
keySeen[sec.Key] = true
|
||||
chapterSort[sec.Key] = order
|
||||
out = append(out, plannedSection{
|
||||
key: sec.Key, title: title, content: sec.Content, sort: order,
|
||||
})
|
||||
order++
|
||||
}
|
||||
|
||||
childCount := map[string]int{}
|
||||
for _, sec := range b.Sections {
|
||||
if sec.ParentKey == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := chapterSort[sec.ParentKey]; !ok {
|
||||
return nil, errors.New("小节「" + strings.TrimSpace(sec.Title) + "」找不到所属章节")
|
||||
}
|
||||
title := strings.TrimSpace(sec.Title)
|
||||
if title == "" {
|
||||
return nil, errors.New("存在标题为空的小节")
|
||||
}
|
||||
if err := validateSectionText(title, sec.Content); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, plannedSection{
|
||||
key: sec.Key,
|
||||
parentKey: sec.ParentKey,
|
||||
title: title,
|
||||
content: sec.Content,
|
||||
sort: childCount[sec.ParentKey],
|
||||
})
|
||||
childCount[sec.ParentKey]++
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func validateSectionText(title, content string) error {
|
||||
if len([]rune(title)) > 200 {
|
||||
return errors.New("章节标题不能超过 200 字:" + title)
|
||||
}
|
||||
if len([]rune(content)) > MaxSectionContent {
|
||||
return errors.New("章节正文不能超过 100000 字:" + title)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkPlannedFiles 预检附件:数量、扩展名、ZIP 路径、声明大小、包内是否存在
|
||||
func (imp *bookImporter) checkPlannedFiles(p bookImportPlan) error {
|
||||
if len(p.book.Files) > MaxLibraryFilesPerDoc {
|
||||
return errors.New("附件数量超过上限(最多 20 个)")
|
||||
}
|
||||
maxB := imp.s.maxBytes()
|
||||
for _, f := range p.book.Files {
|
||||
if f.Missing || f.Stored == "" {
|
||||
continue
|
||||
}
|
||||
rel, ok := cleanZipRel(f.Stored)
|
||||
if !ok || !strings.HasPrefix(rel, "files/") {
|
||||
return errors.New("附件路径非法:" + f.Stored)
|
||||
}
|
||||
name := sanitizeFilename(f.Name)
|
||||
if name == "" || !LibraryExtAllowed(ExtOfFilename(name)) {
|
||||
return errors.New("附件格式不受支持:" + f.Name)
|
||||
}
|
||||
zf, ok := imp.entries[p.dir+rel]
|
||||
if !ok {
|
||||
return errors.New("备份包缺少附件文件:" + f.Name)
|
||||
}
|
||||
if zf.UncompressedSize64 > uint64(maxB) {
|
||||
return errors.New("附件超过大小上限:" + f.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// planCover 返回内嵌封面 ZIP 条目(无则 nil)
|
||||
func (imp *bookImporter) planCover(p bookImportPlan) (*zip.File, error) {
|
||||
cf := strings.TrimSpace(p.book.CoverFile)
|
||||
if cf == "" {
|
||||
return nil, nil
|
||||
}
|
||||
rel, ok := cleanZipRel(cf)
|
||||
if !ok || strings.Contains(rel, "/") {
|
||||
return nil, errors.New("封面路径非法:" + cf)
|
||||
}
|
||||
zf, ok := imp.entries[p.dir+rel]
|
||||
if !ok {
|
||||
return nil, errors.New("备份包缺少封面文件")
|
||||
}
|
||||
if zf.UncompressedSize64 > uint64(ImageMaxBytes) {
|
||||
return nil, errors.New("封面不能超过 5MB")
|
||||
}
|
||||
return zf, nil
|
||||
}
|
||||
|
||||
// ---------- 落盘 ----------
|
||||
|
||||
// createSections 两趟写入:先建章(key→新ID),再建节(父引用映射后的章 ID)
|
||||
func (imp *bookImporter) createSections(tx *gorm.DB, docID uint, sections []plannedSection) error {
|
||||
keyToID := make(map[string]uint, len(sections))
|
||||
for i := range sections {
|
||||
ps := §ions[i]
|
||||
if ps.parentKey != "" {
|
||||
continue
|
||||
}
|
||||
sec := &model.LibrarySection{DocID: docID, Title: ps.title, Content: ps.content, SortOrder: ps.sort}
|
||||
if err := tx.Create(sec).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
keyToID[ps.key] = sec.ID
|
||||
}
|
||||
for i := range sections {
|
||||
ps := §ions[i]
|
||||
if ps.parentKey == "" {
|
||||
continue
|
||||
}
|
||||
parentID, ok := keyToID[ps.parentKey]
|
||||
if !ok {
|
||||
return errors.New("小节找不到所属章节")
|
||||
}
|
||||
sec := &model.LibrarySection{
|
||||
DocID: docID, ParentID: &parentID,
|
||||
Title: ps.title, Content: ps.content, SortOrder: ps.sort,
|
||||
}
|
||||
if err := tx.Create(sec).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// addPlannedFile 从 ZIP 读取附件并复用 AddFile 落盘,随后恢复下载计数与排序
|
||||
func (imp *bookImporter) addPlannedFile(
|
||||
p bookImportPlan, docID uint, mf libraryExportFile,
|
||||
) (*model.LibraryFile, *LibraryImportFailure) {
|
||||
rel, _ := cleanZipRel(mf.Stored)
|
||||
zf, ok := imp.entries[p.dir+rel]
|
||||
if !ok {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "备份包缺少附件文件:"+mf.Name)
|
||||
}
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "读取附件失败:"+mf.Name)
|
||||
}
|
||||
defer rc.Close()
|
||||
f, err := imp.s.AddFile(docID, imp.userID, mf.Name, io.LimitReader(rc, imp.s.maxBytes()+1))
|
||||
if err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "附件恢复失败「"+mf.Name+"」:"+err.Error())
|
||||
}
|
||||
if err := imp.s.db.Model(&model.LibraryFile{}).Where("id = ?", f.ID).
|
||||
UpdateColumns(map[string]interface{}{
|
||||
"download_count": mf.DownloadCount,
|
||||
"sort_order": mf.SortOrder,
|
||||
}).Error; err != nil {
|
||||
return nil, imp.fail(p, libraryImportReasonFailed, "附件信息写入失败:"+mf.Name)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// materializeCover 校验图片魔数后以随机名落盘 uploads/images,返回 URL/尺寸/磁盘路径
|
||||
func (imp *bookImporter) materializeCover(zf *zip.File) (string, int, int, string, error) {
|
||||
if imp.s.uploadsDir == "" {
|
||||
return "", 0, 0, "", errors.New("未配置上传目录")
|
||||
}
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
defer rc.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(rc, ImageMaxBytes+1))
|
||||
if err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
if int64(len(data)) > ImageMaxBytes {
|
||||
return "", 0, 0, "", errors.New("封面不能超过 5MB")
|
||||
}
|
||||
format, err := detectImageFormat(data)
|
||||
if err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
width, height, err := decodeImageSizeReader(bytes.NewReader(data), format.mime)
|
||||
if err != nil || width < 1 || height < 1 {
|
||||
return "", 0, 0, "", errors.New("无法解析封面图片")
|
||||
}
|
||||
if width > ImageMaxDim || height > ImageMaxDim {
|
||||
return "", 0, 0, "", errors.New("封面边长不能超过 4096px")
|
||||
}
|
||||
nameBytes := make([]byte, 16)
|
||||
if _, err := rand.Read(nameBytes); err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
filename := hex.EncodeToString(nameBytes) + format.ext
|
||||
imagesDir := filepath.Join(imp.s.uploadsDir, "images")
|
||||
if err := os.MkdirAll(imagesDir, 0o755); err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
full := filepath.Join(imagesDir, filename)
|
||||
if err := os.WriteFile(full, data, 0o644); err != nil {
|
||||
return "", 0, 0, "", err
|
||||
}
|
||||
return "/uploads/images/" + filename, width, height, full, nil
|
||||
}
|
||||
|
||||
// rollbackCreated create 模式落盘阶段失败:硬删条目/章节/文件行与已落盘文件,释放 slug
|
||||
func (imp *bookImporter) rollbackCreated(docID uint, newFiles []model.LibraryFile, coverDisk string) {
|
||||
_ = imp.s.db.Unscoped().Where("doc_id = ?", docID).Delete(&model.LibrarySection{}).Error
|
||||
_ = imp.s.db.Unscoped().Where("doc_id = ?", docID).Delete(&model.LibraryFile{}).Error
|
||||
_ = imp.s.db.Unscoped().Delete(&model.LibraryDoc{}, docID).Error
|
||||
for i := range newFiles {
|
||||
_ = os.Remove(imp.s.FilePath(&newFiles[i]))
|
||||
}
|
||||
if coverDisk != "" {
|
||||
_ = os.Remove(coverDisk)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- ZIP 工具 ----------
|
||||
|
||||
// cleanZipRel 校验 ZIP 内相对路径:拒绝绝对路径与任何 ../ 穿越段
|
||||
func cleanZipRel(rel string) (string, bool) {
|
||||
p := path.Clean(strings.ReplaceAll(strings.TrimSpace(rel), "\\", "/"))
|
||||
if p == "." || p == "" || path.IsAbs(p) || p == ".." {
|
||||
return "", false
|
||||
}
|
||||
for _, seg := range strings.Split(p, "/") {
|
||||
if seg == ".." {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func readZipJSON(zf *zip.File, v any) error {
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rc.Close()
|
||||
return json.NewDecoder(rc).Decode(v)
|
||||
}
|
||||
354
backend/service/library_import_test.go
Normal file
@@ -0,0 +1,354 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/freefire/jiang13-bbs/model"
|
||||
)
|
||||
|
||||
func encodeJPEGBytes(t *testing.T, w, h int) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, image.NewRGBA(image.Rect(0, 0, w, h)), &jpeg.Options{Quality: 80}); err != nil {
|
||||
t.Fatalf("encode jpeg: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// writeExportZipFile 把内存导出包落盘为临时 zip(模拟 handler 上传后的临时文件)
|
||||
func writeExportZipFile(t *testing.T, exp *LibraryExport) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(t.TempDir(), "export.zip")
|
||||
f, err := os.Create(p)
|
||||
if err != nil {
|
||||
t.Fatalf("create temp zip: %v", err)
|
||||
}
|
||||
if err := exp.WriteZip(f); err != nil {
|
||||
t.Fatalf("write export zip: %v", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatalf("close temp zip: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// writeZipFileMap 手工构造 ZIP(用于非法包测试)
|
||||
func writeZipFileMap(t *testing.T, entries map[string]string) string {
|
||||
t.Helper()
|
||||
buf := new(bytes.Buffer)
|
||||
zw := zip.NewWriter(buf)
|
||||
for name, content := range entries {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatalf("zip create %s: %v", name, err)
|
||||
}
|
||||
if _, err := io.WriteString(w, content); err != nil {
|
||||
t.Fatalf("zip write %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatalf("zip close: %v", err)
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "in.zip")
|
||||
if err := os.WriteFile(p, buf.Bytes(), 0o644); err != nil {
|
||||
t.Fatalf("write temp zip: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func assertReportOK(t *testing.T, rep *LibraryImportReport, total int) {
|
||||
t.Helper()
|
||||
if rep == nil {
|
||||
t.Fatal("报告为空")
|
||||
}
|
||||
if rep.Total != total {
|
||||
t.Fatalf("total = %d, want %d", rep.Total, total)
|
||||
}
|
||||
if len(rep.Failed) != 0 {
|
||||
t.Fatalf("存在失败记录: %+v", rep.Failed)
|
||||
}
|
||||
if len(rep.Imported) != total {
|
||||
t.Fatalf("imported = %d, want %d", len(rep.Imported), total)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLibraryImportBookRoundTrip 单本包:导出 → 导入 → 冲突跳过 → 覆盖导入
|
||||
func TestLibraryImportBookRoundTrip(t *testing.T) {
|
||||
// ---- 源库 ----
|
||||
src, _ := newLibraryTestService(t)
|
||||
srcUploads := t.TempDir()
|
||||
src.WithUploadsDir(srcUploads)
|
||||
docID, storedName := seedBookForExport(t, src, srcUploads)
|
||||
|
||||
// 制造两次下载,验证计数随包保留
|
||||
var srcFile model.LibraryFile
|
||||
if err := src.db.Where("stored_name = ?", storedName).First(&srcFile).Error; err != nil {
|
||||
t.Fatalf("find source file: %v", err)
|
||||
}
|
||||
src.IncrDownload(srcFile.ID)
|
||||
src.IncrDownload(srcFile.ID)
|
||||
|
||||
exp, err := src.BuildBookExport(docID)
|
||||
if err != nil {
|
||||
t.Fatalf("build export: %v", err)
|
||||
}
|
||||
zipPath := writeExportZipFile(t, exp)
|
||||
exp.Close()
|
||||
|
||||
// ---- 目标库(空库)----
|
||||
dst, _ := newLibraryTestService(t)
|
||||
dstUploads := t.TempDir()
|
||||
dst.WithUploadsDir(dstUploads)
|
||||
|
||||
// 1) create 导入
|
||||
rep, err := dst.ImportLibraryZip(zipPath, LibraryImportModeCreate, 7)
|
||||
if err != nil {
|
||||
t.Fatalf("import: %v", err)
|
||||
}
|
||||
assertReportOK(t, rep, 1)
|
||||
item := rep.Imported[0]
|
||||
if item.Slug != "dao-jia" || item.Action != "created" || item.Sections != 2 || item.Files != 1 {
|
||||
t.Fatalf("导入条目异常: %+v", item)
|
||||
}
|
||||
|
||||
var doc model.LibraryDoc
|
||||
if err := dst.db.Where("slug = ?", "dao-jia").First(&doc).Error; err != nil {
|
||||
t.Fatalf("find imported doc: %v", err)
|
||||
}
|
||||
if doc.Title != "道家研究" || doc.Description != "# 介绍" || !doc.Published {
|
||||
t.Fatalf("元信息恢复不正确: %+v", doc)
|
||||
}
|
||||
if doc.Author != "老子" {
|
||||
t.Fatalf("作者恢复不正确: %q", doc.Author)
|
||||
}
|
||||
if doc.CreatorID != 7 {
|
||||
t.Fatalf("新建导入创建者应为导入操作人,got %d", doc.CreatorID)
|
||||
}
|
||||
if !strings.HasPrefix(doc.CoverURL, "/uploads/images/") || doc.CoverURL == "/uploads/images/cover.jpg" {
|
||||
t.Fatalf("封面 URL 应为重新落盘的随机名,got %q", doc.CoverURL)
|
||||
}
|
||||
if doc.CoverWidth != 120 || doc.CoverHeight != 160 {
|
||||
t.Fatalf("封面尺寸恢复不正确: %dx%d", doc.CoverWidth, doc.CoverHeight)
|
||||
}
|
||||
coverDisk, ok := dst.resolveCoverPath(doc.CoverURL)
|
||||
if !ok {
|
||||
t.Fatalf("封面路径无法解析: %s", doc.CoverURL)
|
||||
}
|
||||
coverData, err := os.ReadFile(coverDisk)
|
||||
if err != nil {
|
||||
t.Fatalf("封面未落盘: %v", err)
|
||||
}
|
||||
if !bytes.HasPrefix(coverData, []byte{0xff, 0xd8, 0xff}) {
|
||||
t.Fatal("封面内容不是 JPEG")
|
||||
}
|
||||
|
||||
// 章节树:章 + 小节父子关系
|
||||
secs, err := dst.ListSections(doc.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("list sections: %v", err)
|
||||
}
|
||||
if len(secs) != 2 {
|
||||
t.Fatalf("章节数 = %d, want 2", len(secs))
|
||||
}
|
||||
var chapter, child *model.LibrarySection
|
||||
for i := range secs {
|
||||
if secs[i].ParentID == nil {
|
||||
chapter = &secs[i]
|
||||
} else {
|
||||
child = &secs[i]
|
||||
}
|
||||
}
|
||||
if chapter == nil || child == nil {
|
||||
t.Fatalf("章节层级不正确: %+v", secs)
|
||||
}
|
||||
if chapter.Title != "第一章" || chapter.SortOrder != 0 {
|
||||
t.Fatalf("章信息不正确: %+v", chapter)
|
||||
}
|
||||
if child.Title != "小节" || *child.ParentID != chapter.ID || child.SortOrder != 0 {
|
||||
t.Fatalf("小节信息不正确: %+v", child)
|
||||
}
|
||||
|
||||
// 附件:重新随机落盘、内容与下载计数保留
|
||||
var files []model.LibraryFile
|
||||
if err := dst.db.Where("doc_id = ?", doc.ID).Find(&files).Error; err != nil {
|
||||
t.Fatalf("list files: %v", err)
|
||||
}
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("附件数 = %d, want 1", len(files))
|
||||
}
|
||||
nf := files[0]
|
||||
if nf.Name != "manual.epub" || nf.DownloadCount != 2 || nf.StoredName == srcFile.StoredName {
|
||||
t.Fatalf("附件恢复不正确: %+v", nf)
|
||||
}
|
||||
data, err := os.ReadFile(dst.FilePath(&nf))
|
||||
if err != nil {
|
||||
t.Fatalf("附件未落盘: %v", err)
|
||||
}
|
||||
if string(data) != "EPUB-FILE-BYTES" {
|
||||
t.Fatalf("附件内容不正确: %q", data)
|
||||
}
|
||||
firstCoverURL := doc.CoverURL
|
||||
|
||||
// 2) 再次 create:冲突跳过
|
||||
rep2, err := dst.ImportLibraryZip(zipPath, LibraryImportModeCreate, 7)
|
||||
if err != nil {
|
||||
t.Fatalf("re-import: %v", err)
|
||||
}
|
||||
if rep2.Total != 1 || len(rep2.Imported) != 0 || len(rep2.Failed) != 1 {
|
||||
t.Fatalf("冲突报告异常: %+v", rep2)
|
||||
}
|
||||
if rep2.Failed[0].Reason != libraryImportReasonConflict {
|
||||
t.Fatalf("失败原因应为 conflict,got %q", rep2.Failed[0].Reason)
|
||||
}
|
||||
var docCount int64
|
||||
dst.db.Model(&model.LibraryDoc{}).Count(&docCount)
|
||||
if docCount != 1 {
|
||||
t.Fatalf("冲突跳过后书库数量异常: %d", docCount)
|
||||
}
|
||||
|
||||
// 3) overwrite:先加一个计划外附件与旧封面,导入后应被整体替换
|
||||
extra, err := dst.AddFile(doc.ID, 7, "extra.txt", bytes.NewReader([]byte("EXTRA-BYTES")))
|
||||
if err != nil {
|
||||
t.Fatalf("add extra: %v", err)
|
||||
}
|
||||
extraPath := dst.FilePath(extra)
|
||||
if _, err := os.Stat(extraPath); err != nil {
|
||||
t.Fatalf("extra 未先落盘: %v", err)
|
||||
}
|
||||
|
||||
rep3, err := dst.ImportLibraryZip(zipPath, LibraryImportModeOverwrite, 7)
|
||||
if err != nil {
|
||||
t.Fatalf("overwrite import: %v", err)
|
||||
}
|
||||
assertReportOK(t, rep3, 1)
|
||||
if rep3.Imported[0].Action != "overwritten" {
|
||||
t.Fatalf("动作应为 overwritten,got %q", rep3.Imported[0].Action)
|
||||
}
|
||||
|
||||
dst.db.Model(&model.LibraryDoc{}).Count(&docCount)
|
||||
if docCount != 1 {
|
||||
t.Fatalf("覆盖后书库数量异常: %d", docCount)
|
||||
}
|
||||
var doc2 model.LibraryDoc
|
||||
if err := dst.db.Where("slug = ?", "dao-jia").First(&doc2).Error; err != nil {
|
||||
t.Fatalf("find overwritten doc: %v", err)
|
||||
}
|
||||
if secs2, err := dst.ListSections(doc2.ID); err != nil || len(secs2) != 2 {
|
||||
t.Fatalf("覆盖后章节异常: %d %v", len(secs2), err)
|
||||
}
|
||||
if doc2.Author != "老子" || doc2.CreatorID != 7 {
|
||||
t.Fatalf("覆盖后作者/创建者异常: author=%q creator=%d", doc2.Author, doc2.CreatorID)
|
||||
}
|
||||
var files2 []model.LibraryFile
|
||||
if err := dst.db.Where("doc_id = ?", doc2.ID).Find(&files2).Error; err != nil || len(files2) != 1 {
|
||||
t.Fatalf("覆盖后附件数量异常: %d %v", len(files2), err)
|
||||
}
|
||||
if files2[0].Name != "manual.epub" || files2[0].DownloadCount != 2 {
|
||||
t.Fatalf("覆盖后附件内容异常: %+v", files2[0])
|
||||
}
|
||||
if _, err := os.Stat(extraPath); !os.IsNotExist(err) {
|
||||
t.Fatalf("旧附件磁盘文件应被删除,err=%v", err)
|
||||
}
|
||||
oldCoverDisk, _ := dst.resolveCoverPath(firstCoverURL)
|
||||
if _, err := os.Stat(oldCoverDisk); !os.IsNotExist(err) {
|
||||
t.Fatalf("旧封面磁盘文件应被删除,err=%v", err)
|
||||
}
|
||||
if doc2.CoverURL == firstCoverURL {
|
||||
t.Fatal("覆盖后封面应重新落盘为新文件")
|
||||
}
|
||||
newCoverDisk, _ := dst.resolveCoverPath(doc2.CoverURL)
|
||||
if _, err := os.ReadFile(newCoverDisk); err != nil {
|
||||
t.Fatalf("新封面未落盘: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLibraryImportAll 全库包往返
|
||||
func TestLibraryImportAll(t *testing.T) {
|
||||
src, _ := newLibraryTestService(t)
|
||||
srcUploads := t.TempDir()
|
||||
src.WithUploadsDir(srcUploads)
|
||||
if _, err := src.Create(&LibraryInput{Slug: "second-book", Title: "第二本"}); err != nil {
|
||||
t.Fatalf("create second doc: %v", err)
|
||||
}
|
||||
seedBookForExport(t, src, srcUploads)
|
||||
|
||||
exp, err := src.BuildAllExport()
|
||||
if err != nil {
|
||||
t.Fatalf("build all export: %v", err)
|
||||
}
|
||||
zipPath := writeExportZipFile(t, exp)
|
||||
exp.Close()
|
||||
|
||||
dst, _ := newLibraryTestService(t)
|
||||
dst.WithUploadsDir(t.TempDir())
|
||||
rep, err := dst.ImportLibraryZip(zipPath, LibraryImportModeCreate, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("import all: %v", err)
|
||||
}
|
||||
assertReportOK(t, rep, 2)
|
||||
slugs := map[string]bool{}
|
||||
for _, it := range rep.Imported {
|
||||
slugs[it.Slug] = true
|
||||
}
|
||||
if !slugs["dao-jia"] || !slugs["second-book"] {
|
||||
t.Fatalf("导入书集不正确: %+v", slugs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLibraryImportRejectBadPackage 非法包整体拒绝
|
||||
func TestLibraryImportRejectBadPackage(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
s.WithUploadsDir(t.TempDir())
|
||||
|
||||
badPath := filepath.Join(t.TempDir(), "bad.zip")
|
||||
if err := os.WriteFile(badPath, []byte("this is not a zip"), 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
if _, err := s.ImportLibraryZip(badPath, LibraryImportModeCreate, 1); !errors.Is(err, ErrLibraryImportBadZip) {
|
||||
t.Fatalf("非 zip 应返回 ErrLibraryImportBadZip,got %v", err)
|
||||
}
|
||||
|
||||
noManifest := writeZipFileMap(t, map[string]string{"files/a.epub": "x"})
|
||||
if _, err := s.ImportLibraryZip(noManifest, LibraryImportModeCreate, 1); !errors.Is(err, ErrLibraryImportFormat) {
|
||||
t.Fatalf("缺清单应返回 ErrLibraryImportFormat,got %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.ImportLibraryZip(badPath, "bogus", 1); !errors.Is(err, ErrLibraryImportMode) {
|
||||
t.Fatalf("非法模式应返回 ErrLibraryImportMode,got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCleanZipRel 路径穿越校验
|
||||
func TestCleanZipRel(t *testing.T) {
|
||||
cases := []struct {
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{"", false},
|
||||
{".", false},
|
||||
{"..", false},
|
||||
{"../evil", false},
|
||||
{"a/../../b", false},
|
||||
{"/etc/passwd", false},
|
||||
{`docs\..\..\x`, false},
|
||||
{"files/a.epub", true},
|
||||
{"docs/x/book.json", true},
|
||||
{`docs\x/cover.jpg`, true},
|
||||
{"a//b", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
_, ok := cleanZipRel(tc.in)
|
||||
if ok != tc.want {
|
||||
t.Errorf("cleanZipRel(%q) = %v, want %v", tc.in, ok, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ func newLibraryTestService(t *testing.T) (*LibraryService, string) {
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.LibraryDoc{}, &model.LibraryFile{}, &model.LibrarySection{}); err != nil {
|
||||
if err := db.AutoMigrate(&model.User{}, &model.LibraryDoc{}, &model.LibraryFile{}, &model.LibrarySection{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
@@ -45,6 +45,7 @@ func TestLibraryNormalize(t *testing.T) {
|
||||
{"标题为空", func(i *LibraryInput) { i.Title = " " }, "标题不能为空"},
|
||||
{"标题超限", func(i *LibraryInput) { i.Title = strings.Repeat("书", 201) }, "标题不能超过"},
|
||||
{"介绍超限", func(i *LibraryInput) { i.Description = strings.Repeat("介", 20001) }, "介绍不能超过"},
|
||||
{"作者超限", func(i *LibraryInput) { i.Author = strings.Repeat("作", 101) }, "作者不能超过"},
|
||||
{"合法", func(i *LibraryInput) {}, ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
@@ -63,6 +64,58 @@ func TestLibraryNormalize(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibraryAuthorAndCreator(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
user := &model.User{Username: "curator", Nickname: "馆长", Avatar: "/a.png"}
|
||||
if err := s.db.Create(user).Error; err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
|
||||
pub := true
|
||||
doc, err := s.Create(&LibraryInput{
|
||||
Slug: "authored", Title: "署名本", Author: " 鲁迅 ", Published: &pub,
|
||||
}, user.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
if doc.Author != "鲁迅" || doc.CreatorID != user.ID {
|
||||
t.Fatalf("作者应裁剪、创建者应落库,got %+v", doc)
|
||||
}
|
||||
|
||||
list, err := s.ListPublished()
|
||||
if err != nil {
|
||||
t.Fatalf("list: %v", err)
|
||||
}
|
||||
if len(list) != 1 || list[0].Author != "鲁迅" {
|
||||
t.Fatalf("列表作者异常: %+v", list)
|
||||
}
|
||||
if c := list[0].Creator; c == nil || c.ID != user.ID || c.Nickname != "馆长" {
|
||||
t.Fatalf("列表创建者摘要异常: %+v", c)
|
||||
}
|
||||
|
||||
detail, err := s.GetPublishedBySlug("authored")
|
||||
if err != nil {
|
||||
t.Fatalf("detail: %v", err)
|
||||
}
|
||||
if detail.Creator == nil || detail.Creator.Username != "curator" {
|
||||
t.Fatalf("详情创建者摘要异常: %+v", detail.Creator)
|
||||
}
|
||||
|
||||
// 作者可清空;更新不改变创建者归属
|
||||
if _, err := s.Update(doc.ID, &LibraryInput{
|
||||
Slug: "authored", Title: "署名本", Author: "", Published: &pub,
|
||||
}); err != nil {
|
||||
t.Fatalf("update: %v", err)
|
||||
}
|
||||
var again model.LibraryDoc
|
||||
if err := s.db.First(&again, doc.ID).Error; err != nil {
|
||||
t.Fatalf("reload: %v", err)
|
||||
}
|
||||
if again.Author != "" || again.CreatorID != user.ID {
|
||||
t.Fatalf("更新后作者/创建者异常: %+v", again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLibrarySlugUnique(t *testing.T) {
|
||||
s, _ := newLibraryTestService(t)
|
||||
if _, err := s.Create(&LibraryInput{Slug: "epub-latest", Title: "A"}); err != nil {
|
||||
|
||||
@@ -30,6 +30,27 @@ var mediaLibraryCategories = []struct {
|
||||
{"brand", "brand", "品牌资源"},
|
||||
}
|
||||
|
||||
// 衍生分类:不对应 uploads 子目录,按附件 source 归类
|
||||
const (
|
||||
mediaCategoryBook = "book"
|
||||
mediaCategoryBookName = "书籍"
|
||||
)
|
||||
|
||||
// mediaCategoryForAttachment 附件在媒体库中的展示分类:
|
||||
// 书库封面 / 正文插图(source=library_cover|library_content)统一归“书籍”,
|
||||
// 其余按 kind 对应磁盘目录分类。
|
||||
func mediaCategoryForAttachment(kind, source string) (key, name string) {
|
||||
if source == model.AttachmentSourceLibraryCover || source == model.AttachmentSourceLibraryContent {
|
||||
return mediaCategoryBook, mediaCategoryBookName
|
||||
}
|
||||
for _, cat := range mediaLibraryCategories {
|
||||
if cat.Key == kind {
|
||||
return cat.Key, cat.Name
|
||||
}
|
||||
}
|
||||
return kind, kind
|
||||
}
|
||||
|
||||
// MediaLibraryItem 媒体库条目
|
||||
type MediaLibraryItem struct {
|
||||
URL string `json:"url"` // 展示地址(有 WebP 时为 WebP)
|
||||
@@ -43,6 +64,7 @@ type MediaLibraryItem struct {
|
||||
Height int `json:"height"`
|
||||
Uploader string `json:"uploader,omitempty"` // 上传者昵称(取自附件记录,无记录为空)
|
||||
UploadedAt *time.Time `json:"uploaded_at,omitempty"`
|
||||
RefCount int `json:"ref_count,omitempty"` // 引用计数(>1 表示内容相同的重复上传共享此文件)
|
||||
SourceURL string `json:"source_url,omitempty"` // 来源回链(帖子/评论锚点/用户主页)
|
||||
SourceLabel string `json:"source_label,omitempty"` // 来源描述(如:帖子《…》下的评论)
|
||||
}
|
||||
@@ -53,6 +75,7 @@ func (s *UploadService) AdminMediaLibrary() ([]MediaLibraryItem, map[string]int,
|
||||
// 附件元数据索引:URL → 记录(联出上传者昵称)
|
||||
type attMeta struct {
|
||||
Kind string
|
||||
Source string
|
||||
URL string
|
||||
MIME string
|
||||
Size int
|
||||
@@ -64,41 +87,49 @@ func (s *UploadService) AdminMediaLibrary() ([]MediaLibraryItem, map[string]int,
|
||||
}
|
||||
var rows []attMeta
|
||||
if err := s.db.Table("attachments").
|
||||
Select("attachments.kind, attachments.url, attachments.mime, attachments.size, attachments.width, attachments.height, attachments.created_at, users.nickname, users.username").
|
||||
Select("attachments.kind, attachments.source, attachments.url, attachments.mime, attachments.size, attachments.width, attachments.height, attachments.created_at, users.nickname, users.username").
|
||||
Joins("LEFT JOIN users ON users.id = attachments.user_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
metaByURL := make(map[string]attMeta, len(rows))
|
||||
// 远程存储对象(/api/media/)不在磁盘上,直接作为条目加入
|
||||
items := make([]MediaLibraryItem, 0, len(rows))
|
||||
categoryName := func(key string) string {
|
||||
for _, cat := range mediaLibraryCategories {
|
||||
if cat.Key == key {
|
||||
return cat.Name
|
||||
}
|
||||
}
|
||||
return key
|
||||
// 同 URL 多条记录(内容寻址去重后,重复上传共享同一文件):
|
||||
// 上传者/时间取最早一条,计数即该文件的引用次数
|
||||
type urlMeta struct {
|
||||
meta attMeta
|
||||
count int
|
||||
}
|
||||
agg := make(map[string]*urlMeta, len(rows))
|
||||
for _, r := range rows {
|
||||
metaByURL[r.URL] = r // 本地文件在磁盘扫描时按 URL 合并元数据
|
||||
if !strings.HasPrefix(r.URL, "/api/media/") {
|
||||
continue
|
||||
if a, ok := agg[r.URL]; ok {
|
||||
a.count++
|
||||
if r.CreatedAt.Before(a.meta.CreatedAt) {
|
||||
a.meta = r
|
||||
}
|
||||
} else {
|
||||
agg[r.URL] = &urlMeta{meta: r, count: 1}
|
||||
}
|
||||
}
|
||||
// 远程存储对象(/api/media/)不在磁盘上,按 URL 去重后直接作为条目加入
|
||||
items := make([]MediaLibraryItem, 0, len(agg))
|
||||
for url, a := range agg {
|
||||
r := a.meta
|
||||
if !strings.HasPrefix(url, "/api/media/") {
|
||||
continue // 本地文件在磁盘扫描时按 URL 合并元数据
|
||||
}
|
||||
if r.Kind != model.AttachmentKindImage && r.Kind != model.AttachmentKindAvatar {
|
||||
continue // 未知 kind 不进媒体库
|
||||
}
|
||||
uploader := r.Nickname
|
||||
if uploader == "" {
|
||||
uploader = r.Username
|
||||
}
|
||||
cat := r.Kind
|
||||
if cat != model.AttachmentKindImage && cat != model.AttachmentKindAvatar {
|
||||
continue // 未知 kind 不进媒体库
|
||||
}
|
||||
catKey, catName := mediaCategoryForAttachment(r.Kind, r.Source)
|
||||
ca := r.CreatedAt
|
||||
items = append(items, MediaLibraryItem{
|
||||
URL: r.URL, Category: cat, CategoryName: categoryName(cat),
|
||||
Name: strings.TrimPrefix(r.URL, "/api/media/"), MIME: r.MIME,
|
||||
URL: url, Category: catKey, CategoryName: catName,
|
||||
Name: strings.TrimPrefix(url, "/api/media/"), MIME: r.MIME,
|
||||
Size: int64(r.Size), Width: r.Width, Height: r.Height,
|
||||
Uploader: uploader, UploadedAt: &ca,
|
||||
Uploader: uploader, UploadedAt: &ca, RefCount: a.count,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -138,8 +169,9 @@ func (s *UploadService) AdminMediaLibrary() ([]MediaLibraryItem, map[string]int,
|
||||
mt := info.ModTime()
|
||||
item.UploadedAt = &mt
|
||||
}
|
||||
if m, ok := metaByURL[url]; ok {
|
||||
if a, ok := agg[url]; ok {
|
||||
// 附件记录有上传者与准确创建时间,覆盖磁盘信息
|
||||
m := a.meta
|
||||
uploader := m.Nickname
|
||||
if uploader == "" {
|
||||
uploader = m.Username
|
||||
@@ -147,12 +179,18 @@ func (s *UploadService) AdminMediaLibrary() ([]MediaLibraryItem, map[string]int,
|
||||
ca := m.CreatedAt
|
||||
item.Uploader = uploader
|
||||
item.UploadedAt = &ca
|
||||
item.RefCount = a.count
|
||||
if m.Size > 0 {
|
||||
item.Size = int64(m.Size)
|
||||
}
|
||||
if m.Width > 0 {
|
||||
item.Width, item.Height = m.Width, m.Height
|
||||
}
|
||||
// 书库封面 / 正文插图改归“书籍”分类
|
||||
if m.Source == model.AttachmentSourceLibraryCover || m.Source == model.AttachmentSourceLibraryContent {
|
||||
item.Category = mediaCategoryBook
|
||||
item.CategoryName = mediaCategoryBookName
|
||||
}
|
||||
}
|
||||
// 无尺寸记录时读图片头解析宽高(失败不阻断,保持 0)
|
||||
if item.Width == 0 && item.Size > 0 && item.Size <= 20<<20 {
|
||||
@@ -243,6 +281,8 @@ func (s *UploadService) attachMediaSources(items []MediaLibraryItem) {
|
||||
postByURL := map[string]postRef{}
|
||||
type commentRef struct {
|
||||
id, postID uint
|
||||
floor uint
|
||||
isRoot bool
|
||||
}
|
||||
commentByURL := map[string]commentRef{}
|
||||
|
||||
@@ -299,6 +339,19 @@ func (s *UploadService) attachMediaSources(items []MediaLibraryItem) {
|
||||
}
|
||||
}
|
||||
|
||||
// 评论锚点改用所属帖内相对楼层号(#comment-{floor},楼中楼追加 -r{id})
|
||||
commentIDs := make([]uint, 0, len(commentByURL))
|
||||
for _, cm := range commentByURL {
|
||||
commentIDs = append(commentIDs, cm.id)
|
||||
}
|
||||
commentAnchors := CommentAnchors(s.db, commentIDs)
|
||||
for u, cm := range commentByURL {
|
||||
if a, ok := commentAnchors[cm.id]; ok {
|
||||
cm.floor, cm.isRoot = a.Floor, a.IsRoot
|
||||
commentByURL[u] = cm
|
||||
}
|
||||
}
|
||||
|
||||
// 评论来源要带宿主帖子标题,一次性补齐
|
||||
postTitle := func(id uint) string {
|
||||
var p model.Post
|
||||
@@ -374,7 +427,15 @@ func (s *UploadService) attachMediaSources(items []MediaLibraryItem) {
|
||||
break
|
||||
}
|
||||
if cm, ok := commentByURL[u]; ok {
|
||||
it.SourceURL = fmt.Sprintf("/post/%d#comment-%d", cm.postID, cm.id)
|
||||
if cm.floor > 0 {
|
||||
if cm.isRoot {
|
||||
it.SourceURL = fmt.Sprintf("/post/%d#comment-%d", cm.postID, cm.floor)
|
||||
} else {
|
||||
it.SourceURL = fmt.Sprintf("/post/%d#comment-%d-r%d", cm.postID, cm.floor, cm.id)
|
||||
}
|
||||
} else {
|
||||
it.SourceURL = fmt.Sprintf("/post/%d", cm.postID)
|
||||
}
|
||||
title := commentPostTitle[cm.postID]
|
||||
if title != "" {
|
||||
it.SourceLabel = "帖子《" + truncate(title, 40) + "》下的评论"
|
||||
|
||||
@@ -25,7 +25,7 @@ func newMediaLibraryService(t *testing.T) (*UploadService, string) {
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.Attachment{}, &model.User{}, &model.Post{}, &model.Comment{}); err != nil {
|
||||
if err := db.AutoMigrate(&model.Attachment{}, &model.Blob{}, &model.User{}, &model.Post{}, &model.Comment{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
@@ -250,8 +250,7 @@ func TestAdminMediaLibraryAttachSources(t *testing.T) {
|
||||
if !ok {
|
||||
t.Fatal("comment image missing")
|
||||
}
|
||||
if cimg.SourceURL != fmt.Sprintf("/post/%d#comment-", post.ID) &&
|
||||
!strings.HasPrefix(cimg.SourceURL, fmt.Sprintf("/post/%d#comment-", post.ID)) {
|
||||
if cimg.SourceURL != fmt.Sprintf("/post/%d#comment-1", post.ID) {
|
||||
t.Fatalf("comment source url wrong: %+v", cimg)
|
||||
}
|
||||
if !strings.Contains(cimg.SourceLabel, "下的评论") {
|
||||
@@ -259,6 +258,139 @@ func TestAdminMediaLibraryAttachSources(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminMediaLibraryBookCategory(t *testing.T) {
|
||||
s, dir := newMediaLibraryService(t)
|
||||
|
||||
// 书籍封面(本地磁盘)与正文插图(远程对象),另有一张普通帖子插图
|
||||
writeMediaFile(t, dir, "images/cover.webp", []byte("fake-webp-bytes"))
|
||||
|
||||
if err := s.db.Create(&model.User{Username: "alice", Nickname: "爱丽丝"}).Error; err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
var alice model.User
|
||||
if err := s.db.Where("username = ?", "alice").First(&alice).Error; err != nil {
|
||||
t.Fatalf("load user: %v", err)
|
||||
}
|
||||
created := time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC)
|
||||
mkAtt := func(source, url string) {
|
||||
if err := s.db.Create(&model.Attachment{
|
||||
UserID: alice.ID, Kind: model.AttachmentKindImage, Source: source,
|
||||
URL: url, MIME: "image/webp", Size: 100, Width: 10, Height: 10,
|
||||
CreatedAt: created,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create attachment %s: %v", source, err)
|
||||
}
|
||||
}
|
||||
mkAtt(model.AttachmentSourceLibraryCover, "/uploads/images/cover.webp")
|
||||
mkAtt(model.AttachmentSourceLibraryContent, "/api/media/book-content")
|
||||
mkAtt(model.AttachmentSourcePost, "/api/media/post-image")
|
||||
|
||||
items, counts, err := s.AdminMediaLibrary()
|
||||
if err != nil {
|
||||
t.Fatalf("AdminMediaLibrary: %v", err)
|
||||
}
|
||||
byURL := map[string]MediaLibraryItem{}
|
||||
for _, it := range items {
|
||||
byURL[it.URL] = it
|
||||
}
|
||||
|
||||
// 封面(磁盘)与正文插图(远程)都归“书籍”
|
||||
for _, u := range []string{"/uploads/images/cover.webp", "/api/media/book-content"} {
|
||||
it, ok := byURL[u]
|
||||
if !ok {
|
||||
t.Fatalf("%s missing", u)
|
||||
}
|
||||
if it.Category != "book" || it.CategoryName != "书籍" {
|
||||
t.Fatalf("%s should be book category, got %q/%q", u, it.Category, it.CategoryName)
|
||||
}
|
||||
}
|
||||
|
||||
// 普通帖子插图仍归 image
|
||||
if post := byURL["/api/media/post-image"]; post.Category != "image" {
|
||||
t.Fatalf("post image should stay image category, got %q", post.Category)
|
||||
}
|
||||
|
||||
if counts["book"] != 2 || counts["image"] != 1 {
|
||||
t.Fatalf("counts wrong: %v", counts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminMediaLibraryDedupAggregation(t *testing.T) {
|
||||
s, dir := newMediaLibraryService(t)
|
||||
|
||||
writeMediaFile(t, dir, "images/dup.webp", []byte("fake-webp-bytes"))
|
||||
|
||||
mkUser := func(username, nickname string) model.User {
|
||||
if err := s.db.Create(&model.User{Username: username, Nickname: nickname}).Error; err != nil {
|
||||
t.Fatalf("create user: %v", err)
|
||||
}
|
||||
var u model.User
|
||||
if err := s.db.Where("username = ?", username).First(&u).Error; err != nil {
|
||||
t.Fatalf("load user: %v", err)
|
||||
}
|
||||
return u
|
||||
}
|
||||
alice := mkUser("alice", "爱丽丝")
|
||||
bob := mkUser("bob", "阿Bob")
|
||||
|
||||
early := time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC)
|
||||
late := early.Add(2 * time.Hour)
|
||||
|
||||
// 同一张图被两人先后上传(内容寻址去重后共享同一文件/对象)
|
||||
mkAtt := func(u model.User, url string, at time.Time) {
|
||||
if err := s.db.Create(&model.Attachment{
|
||||
UserID: u.ID, Kind: model.AttachmentKindImage,
|
||||
URL: url, MIME: "image/webp",
|
||||
Size: 100, Width: 10, Height: 10, CreatedAt: at,
|
||||
}).Error; err != nil {
|
||||
t.Fatalf("create attachment %s: %v", url, err)
|
||||
}
|
||||
}
|
||||
mkAtt(alice, "/uploads/images/dup.webp", early)
|
||||
mkAtt(bob, "/uploads/images/dup.webp", late)
|
||||
mkAtt(bob, "/api/media/rdup", early)
|
||||
mkAtt(alice, "/api/media/rdup", late)
|
||||
|
||||
items, _, err := s.AdminMediaLibrary()
|
||||
if err != nil {
|
||||
t.Fatalf("AdminMediaLibrary: %v", err)
|
||||
}
|
||||
|
||||
countByURL := map[string]int{}
|
||||
byURL := map[string]MediaLibraryItem{}
|
||||
for _, it := range items {
|
||||
countByURL[it.URL]++
|
||||
byURL[it.URL] = it
|
||||
}
|
||||
|
||||
// 本地去重文件:单个条目,上传者/时间取最早上传的爱丽丝,引用计数 2
|
||||
local, ok := byURL["/uploads/images/dup.webp"]
|
||||
if !ok {
|
||||
t.Fatal("dedup local file missing")
|
||||
}
|
||||
if countByURL["/uploads/images/dup.webp"] != 1 {
|
||||
t.Fatal("dedup local file should appear exactly once")
|
||||
}
|
||||
if local.Uploader != "爱丽丝" || local.RefCount != 2 {
|
||||
t.Fatalf("local dedup meta wrong: %+v", local)
|
||||
}
|
||||
if local.UploadedAt == nil || !local.UploadedAt.Equal(early) {
|
||||
t.Fatalf("local dedup time should be earliest upload, got %v", local.UploadedAt)
|
||||
}
|
||||
|
||||
// 远程对象同 URL 两条记录:也只出一个条目,取最早的 bob
|
||||
remote, ok := byURL["/api/media/rdup"]
|
||||
if !ok {
|
||||
t.Fatal("dedup remote object missing")
|
||||
}
|
||||
if countByURL["/api/media/rdup"] != 1 {
|
||||
t.Fatal("dedup remote object should appear exactly once")
|
||||
}
|
||||
if remote.Uploader != "阿Bob" || remote.RefCount != 2 {
|
||||
t.Fatalf("remote dedup meta wrong: %+v", remote)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaThumb(t *testing.T) {
|
||||
s, dir := newMediaLibraryService(t)
|
||||
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/gif"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
webpenc "github.com/gen2brain/webp"
|
||||
"golang.org/x/image/draw"
|
||||
xwebp "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// 媒体库缩略图:管理后台网格不再直连原图(全量图片一次加载网络压力大)。
|
||||
// 服务端按需生成最长边 480px 的 WebP 缩略图,落盘 .thumbs/(按 URL 哈希命名)缓存,
|
||||
// 源文件更新后(mtime 更新)自动重建。仅覆盖本地 /uploads/ 图片;
|
||||
// 远程存储对象与解码失败(如动图 WebP)由调用方回退原图。
|
||||
// 解码/缩放/编码/原子落盘共用 image_variants.go 的图片处理核心。
|
||||
|
||||
// MediaThumbMaxSide 缩略图最长边(网格单元 ~200px,2x DPR 足够)
|
||||
const MediaThumbMaxSide = 480
|
||||
@@ -70,12 +62,7 @@ func (s *UploadService) MediaThumb(url string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var img image.Image
|
||||
if ext == ".webp" {
|
||||
img, err = xwebp.Decode(bytes.NewReader(data))
|
||||
} else {
|
||||
img, _, err = image.Decode(bytes.NewReader(data))
|
||||
}
|
||||
img, err := decodeImageBytes(data, ext == ".webp")
|
||||
if err != nil {
|
||||
return nil, err // 如动图 WebP,调用方回退原图
|
||||
}
|
||||
@@ -94,21 +81,13 @@ func (s *UploadService) MediaThumb(url string) ([]byte, error) {
|
||||
nh = MediaThumbMaxSide
|
||||
nw = max(1, w*MediaThumbMaxSide/h)
|
||||
}
|
||||
dst := image.NewRGBA(image.Rect(0, 0, nw, nh))
|
||||
draw.CatmullRom.Scale(dst, dst.Bounds(), img, b, draw.Src, nil)
|
||||
dst := scaleImage(img, nw, nh)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := webpenc.Encode(&buf, dst, webpenc.Options{Quality: 78}); err != nil {
|
||||
out, err := encodeLossyWebP(dst, VariantWebPQuality)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 原子落缓存(失败仅影响下次重复生成,不阻断响应)
|
||||
if err := os.MkdirAll(filepath.Dir(thumbPath), 0o755); err == nil {
|
||||
tmp := thumbPath + ".partial"
|
||||
if err := os.WriteFile(tmp, buf.Bytes(), 0o644); err == nil {
|
||||
if err := os.Rename(tmp, thumbPath); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
_ = atomicWriteFile(thumbPath, out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ import (
|
||||
|
||||
type mailPayload struct{ To, Subject, Body string }
|
||||
|
||||
// ErrEmailRegistered 注册发码时邮箱已被占用,handler 据此返回 400 业务提示
|
||||
var ErrEmailRegistered = errors.New("该邮箱已被注册,请直接登录")
|
||||
|
||||
func (o *Operations) smtp(ctx context.Context, c MailConfig, p *mailPayload, id string) error {
|
||||
password, e := o.open(c.Password, "mail:password")
|
||||
if e != nil {
|
||||
@@ -392,6 +395,16 @@ func (o *Operations) SendCode(email, purpose, ip string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
}
|
||||
if purpose == "register" {
|
||||
// 入口拦截:邮箱已被占用则不发码,省一次邮件资源,也给用户明确提示
|
||||
var n int64
|
||||
if e = o.db.Model(&model.User{}).Where("LOWER(email) = ?", email).Count(&n).Error; e != nil {
|
||||
return 0, e
|
||||
}
|
||||
if n > 0 {
|
||||
return 0, ErrEmailRegistered
|
||||
}
|
||||
}
|
||||
code := randomCode()
|
||||
hash := counterKey(email + ":" + purpose + ":" + code)
|
||||
e = o.db.Transaction(func(tx *gorm.DB) error {
|
||||
@@ -402,6 +415,7 @@ func (o *Operations) SendCode(email, purpose, ip string) (int, error) {
|
||||
})
|
||||
return 0, e
|
||||
}
|
||||
|
||||
const (
|
||||
codeVerifyMaxAttempts = 5
|
||||
codeVerifyWindow = 15 * 60 // 秒,与验证码有效期一致
|
||||
|
||||
@@ -16,6 +16,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (o *Operations) s3(c StorageConfig) (*minio.Client, error) {
|
||||
@@ -137,6 +139,65 @@ func (o *Operations) StoreFile(path, mimeType string, public bool) (string, erro
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// blobObjectID 内容寻址对象的稳定 ID:公开/私有加不同前缀,同字节也不共享可见性。
|
||||
func blobObjectID(hash string, public bool) string {
|
||||
if public {
|
||||
return "pub_" + hash
|
||||
}
|
||||
return "prv_" + hash
|
||||
}
|
||||
|
||||
// StoreFileHashed 按内容 hash 幂等上传:同一 (hash, public) 只存一份,重复上传跳过传输。
|
||||
// 本地后端返回空 ID(文件留在本地 blob 目录,由调用方做引用计数)。
|
||||
func (o *Operations) StoreFileHashed(path, mimeType string, public bool, hash string) (string, error) {
|
||||
v, version, e := o.read(o.db, "storage")
|
||||
if e != nil {
|
||||
return "", errors.New("读取存储配置失败")
|
||||
}
|
||||
c := *v.(*StorageConfig)
|
||||
if c.Backend == "local" {
|
||||
return "", nil
|
||||
}
|
||||
id := blobObjectID(hash, public)
|
||||
// hash 相同字节必然相同:对象已存在时直接复用,省掉整次上传
|
||||
var existing model.StoredObject
|
||||
if e := o.db.First(&existing, "id = ?", id).Error; e == nil {
|
||||
return id, nil
|
||||
} else if !errors.Is(e, gorm.ErrRecordNotFound) {
|
||||
return "", e
|
||||
}
|
||||
client, e := o.s3(c)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
f, e := os.Open(path)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
stat, e := f.Stat()
|
||||
if e != nil {
|
||||
_ = f.Close()
|
||||
return "", e
|
||||
}
|
||||
key := c.Prefix + "objects/" + id
|
||||
if _, e = client.PutObject(ctx, c.Bucket, key, f, stat.Size(), minio.PutObjectOptions{ContentType: mimeType, DisableMultipart: true}); e != nil {
|
||||
_ = f.Close()
|
||||
return "", errors.New("上传到 S3 失败,当前目标未自动切换")
|
||||
}
|
||||
_ = f.Close()
|
||||
obj := model.StoredObject{ID: id, ConfigName: fmt.Sprintf("storage-%d", version), Key: key, MIME: mimeType, Public: public}
|
||||
if e = o.db.Create(&obj).Error; e != nil {
|
||||
if isUniqueConflict(e) { // 并发:另一请求已写入同内容对象,直接复用
|
||||
return id, nil
|
||||
}
|
||||
_ = client.RemoveObject(ctx, c.Bucket, key, minio.RemoveObjectOptions{})
|
||||
return "", errors.New("保存文件记录失败")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
func (o *Operations) OpenObject(ctx context.Context, id string, requirePublic bool) (io.ReadCloser, string, error) {
|
||||
var obj model.StoredObject
|
||||
if e := o.db.First(&obj, "id = ?", id).Error; e != nil {
|
||||
|
||||
@@ -72,18 +72,18 @@ type NewUserItem struct {
|
||||
|
||||
// OverviewData 首页聚合数据
|
||||
type OverviewData struct {
|
||||
Stats OverviewStats `json:"stats"`
|
||||
Hot []PostListItem `json:"hot"`
|
||||
ActiveUsers []ActiveUser `json:"active_users"`
|
||||
Boards []BoardCount `json:"boards"`
|
||||
Announcements []AnnouncementItem `json:"announcements"`
|
||||
AnnouncementsTotal int64 `json:"announcements_total"`
|
||||
SidebarPages []SidebarPageItem `json:"sidebar_pages"`
|
||||
NewUsers []NewUserItem `json:"new_users"`
|
||||
Checkin *CheckinStatus `json:"checkin,omitempty"`
|
||||
Ads []PublicAdItem `json:"ads"`
|
||||
AdsPanelTitle string `json:"ads_panel_title"`
|
||||
AdsEnabled bool `json:"ads_enabled"`
|
||||
Stats OverviewStats `json:"stats"`
|
||||
Hot []PostListItem `json:"hot"`
|
||||
ActiveUsers []ActiveUser `json:"active_users"`
|
||||
Boards []BoardCount `json:"boards"`
|
||||
Announcements []AnnouncementItem `json:"announcements"`
|
||||
AnnouncementsTotal int64 `json:"announcements_total"`
|
||||
SidebarPages []SidebarPageItem `json:"sidebar_pages"`
|
||||
NewUsers []NewUserItem `json:"new_users"`
|
||||
Checkin *CheckinStatus `json:"checkin,omitempty"`
|
||||
Ads []PublicAdItem `json:"ads"`
|
||||
AdsPanelTitle string `json:"ads_panel_title"`
|
||||
AdsEnabled bool `json:"ads_enabled"`
|
||||
Sponsors []PublicSponsorItem `json:"sponsors"`
|
||||
SponsorsPanelTitle string `json:"sponsors_panel_title"`
|
||||
SponsorsEnabled bool `json:"sponsors_enabled"`
|
||||
|
||||
@@ -457,37 +457,37 @@ type PostAttachmentDTO struct {
|
||||
|
||||
// PostDetail 帖子详情(含可见性裁剪与附件)
|
||||
type PostDetail struct {
|
||||
ID uint `json:"id"`
|
||||
BoardID uint `json:"board_id"`
|
||||
UserID uint `json:"user_id"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Tags string `json:"tags"`
|
||||
PostType string `json:"post_type"`
|
||||
ContentAccess string `json:"content_access"`
|
||||
AccessPoints int `json:"access_points"`
|
||||
TypeMeta string `json:"type_meta"`
|
||||
TypeStatus string `json:"type_status,omitempty"`
|
||||
Pinned int `json:"pinned"`
|
||||
Recommended bool `json:"recommended"`
|
||||
Locked bool `json:"locked"` // 管理员手动锁定:普通用户不可编辑/回复(staff 豁免)
|
||||
Status string `json:"status"`
|
||||
LikeCount int `json:"like_count"`
|
||||
ViewCount int `json:"view_count"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
Liked bool `json:"liked"`
|
||||
Favorited bool `json:"favorited"` // 当前查看者是否已收藏(详情接口实时填充)
|
||||
Edited bool `json:"edited"` // 是否存在编辑历史快照(决定"更新于/编辑历史"入口展示)
|
||||
ID uint `json:"id"`
|
||||
BoardID uint `json:"board_id"`
|
||||
UserID uint `json:"user_id"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Tags string `json:"tags"`
|
||||
PostType string `json:"post_type"`
|
||||
ContentAccess string `json:"content_access"`
|
||||
AccessPoints int `json:"access_points"`
|
||||
TypeMeta string `json:"type_meta"`
|
||||
TypeStatus string `json:"type_status,omitempty"`
|
||||
Pinned int `json:"pinned"`
|
||||
Recommended bool `json:"recommended"`
|
||||
Locked bool `json:"locked"` // 管理员手动锁定:普通用户不可编辑/回复(staff 豁免)
|
||||
Status string `json:"status"`
|
||||
LikeCount int `json:"like_count"`
|
||||
ViewCount int `json:"view_count"`
|
||||
CommentCount int `json:"comment_count"`
|
||||
Liked bool `json:"liked"`
|
||||
Favorited bool `json:"favorited"` // 当前查看者是否已收藏(详情接口实时填充)
|
||||
Edited bool `json:"edited"` // 是否存在编辑历史快照(决定"更新于/编辑历史"入口展示)
|
||||
// 最后一条已发布评论时间;null=无回复(旧帖判定回落 created_at)
|
||||
LastReplyAt *time.Time `json:"last_reply_at,omitempty"`
|
||||
// 旧帖回复确认提示:按查看者实时计算,命中才返回;前端存在即弹确认框
|
||||
NecroReply *NecroReplyHint `json:"necro_reply,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
ContentLocked bool `json:"content_locked"`
|
||||
AccessHint string `json:"access_hint,omitempty"`
|
||||
NecroReply *NecroReplyHint `json:"necro_reply,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Board model.Board `json:"board"`
|
||||
User model.User `json:"user"`
|
||||
ContentLocked bool `json:"content_locked"`
|
||||
AccessHint string `json:"access_hint,omitempty"`
|
||||
Attachments []PostAttachmentDTO `json:"attachments"`
|
||||
Question *QuestionState `json:"question,omitempty"`
|
||||
Poll *PollState `json:"poll,omitempty"`
|
||||
@@ -620,7 +620,7 @@ func buildPostDetail(post *model.Post) *PostDetail {
|
||||
ContentAccess: model.NormalizeContentAccess(post.ContentAccess),
|
||||
AccessPoints: post.AccessPoints, TypeMeta: post.TypeMeta,
|
||||
TypeStatus: ComputeTypeStatus(post.PostType, post.TypeMeta),
|
||||
Pinned: post.Pinned, Recommended: post.Recommended, Locked: post.Locked, Status: post.Status,
|
||||
Pinned: post.Pinned, Recommended: post.Recommended, Locked: post.Locked, Status: post.Status,
|
||||
LikeCount: post.LikeCount, ViewCount: post.ViewCount, CommentCount: post.CommentCount,
|
||||
Liked: post.Liked, CreatedAt: post.CreatedAt, UpdatedAt: post.UpdatedAt,
|
||||
Board: post.Board, User: post.User,
|
||||
|
||||
@@ -2,10 +2,12 @@ package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unicode/utf8"
|
||||
@@ -145,8 +147,9 @@ func (s *PostFileService) SaveDraftFile(userID uint, originalName string, src io
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// LimitReader 多读 1 字节以区分「刚好上限」与「超限」
|
||||
written, copyErr := io.Copy(f, io.LimitReader(src, maxB+1))
|
||||
// LimitReader 多读 1 字节以区分「刚好上限」与「超限」;落盘同时计算内容 hash
|
||||
hasher := sha256.New()
|
||||
written, copyErr := io.Copy(io.MultiWriter(f, hasher), io.LimitReader(src, maxB+1))
|
||||
_ = f.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
@@ -167,28 +170,45 @@ func (s *PostFileService) SaveDraftFile(userID uint, originalName string, src io
|
||||
return nil, err
|
||||
}
|
||||
|
||||
att := &model.PostAttachment{
|
||||
PostID: 0,
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
StoredName: stored,
|
||||
MIME: mimeType,
|
||||
Size: int(written),
|
||||
PricePoints: pricePoints,
|
||||
}
|
||||
// 内容寻址:私有 blob 以 hash 命名(不带扩展名,下载时以 att.MIME + 原文件名下发)
|
||||
hash := hex.EncodeToString(hasher.Sum(nil))
|
||||
final := absPath(s.dir, hash)
|
||||
var objectID string
|
||||
if s.ops != nil {
|
||||
id, e := s.ops.StoreFile(full, att.MIME, false)
|
||||
id, e := s.ops.StoreFileHashed(full, mimeType, false, hash)
|
||||
if e != nil {
|
||||
_ = os.Remove(full)
|
||||
return nil, e
|
||||
}
|
||||
att.ObjectID = id
|
||||
objectID = id
|
||||
if id != "" {
|
||||
_ = os.Remove(full)
|
||||
}
|
||||
}
|
||||
if err := s.db.Create(att).Error; err != nil {
|
||||
_ = os.Remove(full)
|
||||
if objectID == "" {
|
||||
if e := placeLocalBlob(full, final); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
|
||||
att := &model.PostAttachment{
|
||||
PostID: 0,
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
StoredName: hash,
|
||||
BlobHash: hash,
|
||||
ObjectID: objectID,
|
||||
MIME: mimeType,
|
||||
Size: int(written),
|
||||
PricePoints: pricePoints,
|
||||
}
|
||||
if err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if e := acquireBlobRef(tx, hash, false, int(written), mimeType, objectID); e != nil {
|
||||
return e
|
||||
}
|
||||
return tx.Create(att).Error
|
||||
}); err != nil {
|
||||
s.releasePostBlobBestEffort(hash)
|
||||
return nil, err
|
||||
}
|
||||
return att, nil
|
||||
@@ -283,14 +303,51 @@ func (s *PostFileService) DeleteOwn(userID, attID uint) error {
|
||||
if att.UserID != userID {
|
||||
return ErrAttachmentForbidden
|
||||
}
|
||||
path := absPath(s.dir, att.StoredName)
|
||||
if err := s.db.Delete(&att).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if att.BlobHash != "" {
|
||||
return s.releasePostBlob(&att)
|
||||
}
|
||||
if s.ops != nil && att.ObjectID != "" {
|
||||
return s.ops.RemoveObject(att.ObjectID)
|
||||
}
|
||||
_ = os.Remove(path)
|
||||
_ = os.Remove(absPath(s.dir, att.StoredName))
|
||||
return nil
|
||||
}
|
||||
|
||||
// releasePostBlob 私有附件 blob 引用计数-1;最后一个引用删除时回收物理文件
|
||||
func (s *PostFileService) releasePostBlob(att *model.PostAttachment) error {
|
||||
b, last, err := releaseBlobRef(s.db, att.BlobHash, false)
|
||||
if err != nil || !last {
|
||||
return err
|
||||
}
|
||||
return s.removePrivateBlobObject(b)
|
||||
}
|
||||
|
||||
// releasePostBlobBestEffort 附件记录落库失败时回滚刚加的引用,错误只记日志
|
||||
func (s *PostFileService) releasePostBlobBestEffort(hash string) {
|
||||
b, last, err := releaseBlobRef(s.db, hash, false)
|
||||
if err != nil {
|
||||
log.Printf("[post-file] 回滚 blob 引用失败 hash=%s: %v", hash, err)
|
||||
return
|
||||
}
|
||||
if !last {
|
||||
return
|
||||
}
|
||||
if err := s.removePrivateBlobObject(b); err != nil {
|
||||
log.Printf("[post-file] 回滚 blob 物理文件失败 hash=%s: %v", hash, err)
|
||||
}
|
||||
}
|
||||
|
||||
// removePrivateBlobObject 引用归零后的物理回收(私有 blob 文件名即 hash,无扩展名)
|
||||
func (s *PostFileService) removePrivateBlobObject(b model.Blob) error {
|
||||
if b.ObjectID != "" && s.ops != nil {
|
||||
return s.ops.RemoveObject(b.ObjectID)
|
||||
}
|
||||
if err := os.Remove(absPath(s.dir, b.Hash)); err != nil && !os.IsNotExist(err) {
|
||||
log.Printf("[post-file] 删除 blob 文件失败 hash=%s: %v", b.Hash, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -472,6 +472,7 @@ func EnsureDeadlineOnPublish(typeMeta, postType string, publishedAt time.Time) (
|
||||
type AcceptedAnswer struct {
|
||||
ID uint `json:"id"`
|
||||
Floor int `json:"floor"`
|
||||
IsRoot bool `json:"is_root"` // false = 楼中楼回复,锚点需 #comment-{floor}-r{id}
|
||||
Content string `json:"content"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Deleted bool `json:"deleted,omitempty"`
|
||||
@@ -736,6 +737,7 @@ func (s *PostService) loadAcceptedAnswer(postID, commentID uint, floor int, view
|
||||
ans := &AcceptedAnswer{
|
||||
ID: c.ID,
|
||||
Floor: floor,
|
||||
IsRoot: c.ParentID == nil,
|
||||
CreatedAt: c.CreatedAt,
|
||||
}
|
||||
staff := c.DeletedAt.Valid && c.DeletedBy != 0 && c.DeletedBy != c.UserID
|
||||
|
||||
@@ -85,6 +85,7 @@ const (
|
||||
RateAdSubmit = "ad_submit" // 广告申购 5/分钟(按 IP)
|
||||
RateCaptcha = "captcha" // 验证码刷新 30/分钟
|
||||
RateTelemetry = "telemetry" // 页面浏览埋点 120/分钟(按 IP)
|
||||
RateSnippet = "snippet" // 代码片段创建/Fork 10/分钟
|
||||
)
|
||||
|
||||
// DefaultRateLimiter 创建默认速率限制器
|
||||
@@ -102,5 +103,6 @@ func DefaultRateLimiter() *RateLimiter {
|
||||
rl.SetLimit(RateAdSubmit, 5) // 广告申购 5/分钟
|
||||
rl.SetLimit(RateCaptcha, 30) // 验证码 30/分钟
|
||||
rl.SetLimit(RateTelemetry, 120) // 埋点 120/分钟
|
||||
rl.SetLimit(RateSnippet, 10) // 代码片段 10/分钟
|
||||
return rl
|
||||
}
|
||||
|
||||
@@ -202,6 +202,7 @@ type PublicSiteSettings struct {
|
||||
BrandMark string `json:"brand_mark"`
|
||||
BrandLogoSize string `json:"brand_logo_size"`
|
||||
BrandLogoFit string `json:"brand_logo_fit"`
|
||||
BrandSloganVisible bool `json:"brand_slogan_visible"`
|
||||
FooterLinks []FooterLink `json:"footer_links"`
|
||||
|
||||
// 积分增长规则(经济规则公开透明,签到卡等可直出)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
sitePageSlugRe = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
|
||||
sitePageSlugRe = regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
|
||||
ErrSitePageNotDeleted = errors.New("仅已删除的单页可彻底删除")
|
||||
)
|
||||
|
||||
|
||||
1022
backend/service/snippet.go
Normal file
@@ -90,7 +90,7 @@ func (s *SettingService) ImportTimelineFromReleases(urls []string) (*TimelineGit
|
||||
client := &http.Client{
|
||||
Timeout: timelineGitHTTPTimeout,
|
||||
Transport: &http.Transport{
|
||||
DialContext: publicOnlyDial,
|
||||
DialContext: publicOnlyDial,
|
||||
TLSHandshakeTimeout: timelineGitHTTPTimeout,
|
||||
ForceAttemptHTTP2: true,
|
||||
},
|
||||
|
||||
@@ -113,46 +113,57 @@ func (s *UploadService) SaveAvatar(userID uint, data []byte) (*model.Attachment,
|
||||
return nil, errors.New("头像尺寸需在 64~512px 之间")
|
||||
}
|
||||
|
||||
nameBytes := make([]byte, 16)
|
||||
if _, err := rand.Read(nameBytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filename := hex.EncodeToString(nameBytes) + ".webp"
|
||||
hash := sha256Hex(data)
|
||||
filename := hash + ".webp"
|
||||
fullPath := filepath.Join(s.dir, "avatars", filename)
|
||||
if err := os.WriteFile(fullPath, data, 0o644); err != nil {
|
||||
return nil, err
|
||||
url := "/uploads/avatars/" + filename
|
||||
var objectID string
|
||||
writeLocal := func() error {
|
||||
if _, err := os.Stat(fullPath); err == nil {
|
||||
return nil // 同内容头像已落盘,字节必然一致,无需重写
|
||||
}
|
||||
return os.WriteFile(fullPath, data, 0o644)
|
||||
}
|
||||
|
||||
att := &model.Attachment{
|
||||
UserID: userID,
|
||||
Kind: model.AttachmentKindAvatar,
|
||||
URL: "/uploads/avatars/" + filename,
|
||||
MIME: "image/webp",
|
||||
Size: len(data),
|
||||
Width: cfg.Width,
|
||||
Height: cfg.Height,
|
||||
}
|
||||
|
||||
if s.ops != nil {
|
||||
id, e := s.ops.StoreFile(fullPath, att.MIME, true)
|
||||
if err := writeLocal(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
id, e := s.ops.StoreFileHashed(fullPath, "image/webp", true, hash)
|
||||
if e != nil {
|
||||
_ = os.Remove(fullPath)
|
||||
return nil, e
|
||||
}
|
||||
objectID = id
|
||||
if id != "" {
|
||||
att.URL = "/api/media/" + id
|
||||
url = "/api/media/" + id
|
||||
_ = os.Remove(fullPath)
|
||||
}
|
||||
} else if err := writeLocal(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 附件记录与用户头像更新在同一事务内完成
|
||||
|
||||
att := &model.Attachment{
|
||||
UserID: userID,
|
||||
Kind: model.AttachmentKindAvatar,
|
||||
URL: url,
|
||||
BlobHash: hash,
|
||||
MIME: "image/webp",
|
||||
Size: len(data),
|
||||
Width: cfg.Width,
|
||||
Height: cfg.Height,
|
||||
}
|
||||
// 附件记录、blob 引用与用户头像更新在同一事务内完成
|
||||
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := acquireBlobRef(tx, hash, true, len(data), "image/webp", objectID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(att).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&model.User{}).Where("id = ?", userID).Update("avatar", att.URL).Error
|
||||
})
|
||||
if err != nil {
|
||||
_ = os.Remove(fullPath) // DB 失败时清理已落盘文件
|
||||
s.releaseBlobBestEffort(hash, true, "/uploads/avatars/"+filename)
|
||||
return nil, err
|
||||
}
|
||||
return att, nil
|
||||
@@ -238,7 +249,7 @@ func (s *UploadService) transcodeImageToWebP(tmp, name, ext string) (string, str
|
||||
}
|
||||
|
||||
// SaveImage 流式保存帖子插图:校验格式/大小/尺寸 → JPEG/PNG 转 WebP → 落盘 → 写 attachments(kind=image)
|
||||
func (s *UploadService) SaveImage(userID uint, src io.Reader) (*model.Attachment, error) {
|
||||
func (s *UploadService) SaveImage(userID uint, src io.Reader, source string) (*model.Attachment, error) {
|
||||
if src == nil {
|
||||
return nil, errors.New("文件为空")
|
||||
}
|
||||
@@ -351,28 +362,51 @@ func (s *UploadService) SaveImage(userID uint, src io.Reader) (*model.Attachment
|
||||
}
|
||||
}
|
||||
|
||||
att := &model.Attachment{
|
||||
UserID: userID,
|
||||
Kind: model.AttachmentKindImage,
|
||||
URL: "/uploads/images/" + storeName,
|
||||
MIME: storeMime,
|
||||
Size: int(storeSize),
|
||||
Width: w,
|
||||
Height: h,
|
||||
// 对最终存储字节做内容寻址(JPEG/PNG 已在上面转成 WebP,同图重复上传才能命中)
|
||||
hash, err := hashFile(storePath)
|
||||
if err != nil {
|
||||
_ = os.Remove(storePath)
|
||||
return nil, err
|
||||
}
|
||||
finalName := hash + strings.ToLower(filepath.Ext(storeName))
|
||||
url := "/uploads/images/" + finalName
|
||||
var objectID string
|
||||
if s.ops != nil {
|
||||
id, e := s.ops.StoreFile(storePath, att.MIME, true)
|
||||
id, e := s.ops.StoreFileHashed(storePath, storeMime, true, hash)
|
||||
if e != nil {
|
||||
_ = os.Remove(storePath)
|
||||
return nil, e
|
||||
}
|
||||
objectID = id
|
||||
if id != "" {
|
||||
att.URL = "/api/media/" + id
|
||||
// 远程后端:以对象 ID 为访问地址,本地临时副本回收
|
||||
url = "/api/media/" + id
|
||||
_ = os.Remove(storePath)
|
||||
} else if e := placeLocalBlob(storePath, filepath.Join(s.dir, "images", finalName)); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
} else if e := placeLocalBlob(storePath, filepath.Join(s.dir, "images", finalName)); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if err := s.db.Create(att).Error; err != nil {
|
||||
_ = os.Remove(storePath)
|
||||
|
||||
att := &model.Attachment{
|
||||
UserID: userID,
|
||||
Kind: model.AttachmentKindImage,
|
||||
Source: normalizeImageSource(source),
|
||||
URL: url,
|
||||
BlobHash: hash,
|
||||
MIME: storeMime,
|
||||
Size: int(storeSize),
|
||||
Width: w,
|
||||
Height: h,
|
||||
}
|
||||
if err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := acquireBlobRef(tx, hash, true, int(storeSize), storeMime, objectID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(att).Error
|
||||
}); err != nil {
|
||||
s.releaseBlobBestEffort(hash, true, url)
|
||||
return nil, err
|
||||
}
|
||||
return att, nil
|
||||
@@ -585,9 +619,20 @@ func (s *UploadService) CopyBackgroundFromMedia(userID, attachmentID uint) (stri
|
||||
return s.SaveBackground(f)
|
||||
}
|
||||
|
||||
// normalizeImageSource 把外部传入的图片来源收敛到白名单,未知值回退为 post
|
||||
func normalizeImageSource(s string) string {
|
||||
switch s {
|
||||
case model.AttachmentSourceLibraryCover, model.AttachmentSourceLibraryContent:
|
||||
return s
|
||||
default:
|
||||
return model.AttachmentSourcePost
|
||||
}
|
||||
}
|
||||
|
||||
// CopyImageFromMedia 把当前用户媒体库里的一张图复制一份新插图(落 uploads/images 并记一条本人附件)
|
||||
// 用于书籍封面等长期引用场景:与原图解耦,原图删除后副本仍可用
|
||||
func (s *UploadService) CopyImageFromMedia(userID, attachmentID uint) (*model.Attachment, error) {
|
||||
// source 决定副本的来源标记(如 library_cover)
|
||||
func (s *UploadService) CopyImageFromMedia(userID, attachmentID uint, source string) (*model.Attachment, error) {
|
||||
var att model.Attachment
|
||||
if err := s.db.Where("id = ? AND user_id = ?", attachmentID, userID).First(&att).Error; err != nil {
|
||||
return nil, errors.New("图片不存在或不属于你")
|
||||
@@ -600,7 +645,7 @@ func (s *UploadService) CopyImageFromMedia(userID, attachmentID uint) (*model.At
|
||||
return nil, e
|
||||
}
|
||||
defer r.Close()
|
||||
return s.SaveImage(userID, r)
|
||||
return s.SaveImage(userID, r, source)
|
||||
}
|
||||
abs, ok := s.safeUploadPath(att.URL)
|
||||
if !ok {
|
||||
@@ -611,7 +656,7 @@ func (s *UploadService) CopyImageFromMedia(userID, attachmentID uint) (*model.At
|
||||
return nil, errors.New("读取图片失败")
|
||||
}
|
||||
defer f.Close()
|
||||
return s.SaveImage(userID, f)
|
||||
return s.SaveImage(userID, f, source)
|
||||
}
|
||||
|
||||
// BackgroundFileExists 确认 URL 对应文件在 backgrounds 目录内
|
||||
@@ -667,6 +712,15 @@ func (s *UploadService) ListMedia(userID uint) ([]model.Attachment, error) {
|
||||
return list, err
|
||||
}
|
||||
|
||||
// FindMediaBySource 按来源查本人附件(存在返回记录,不存在返回 error)
|
||||
func (s *UploadService) FindMediaBySource(userID, attachmentID uint, source string) (*model.Attachment, error) {
|
||||
var att model.Attachment
|
||||
if err := s.db.Where("id = ? AND user_id = ? AND source = ?", attachmentID, userID, source).First(&att).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &att, nil
|
||||
}
|
||||
|
||||
// ErrAttachmentInUse 图片正被帖子内容引用,不可物理删除
|
||||
var ErrAttachmentInUse = errors.New("该图片已被帖子使用,无法删除")
|
||||
|
||||
@@ -701,6 +755,10 @@ func (s *UploadService) DeleteAttachment(userID, attachmentID uint) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if att.BlobHash != "" {
|
||||
return s.releaseAttachmentBlob(&att)
|
||||
}
|
||||
|
||||
if s.ops != nil && strings.HasPrefix(att.URL, "/api/media/") {
|
||||
if e := s.ops.RemoveObject(RemoteObjectID(att.URL)); e != nil {
|
||||
return errors.New("记录已删除,远程文件清理未完成,请联系管理员")
|
||||
@@ -715,4 +773,47 @@ func (s *UploadService) DeleteAttachment(userID, attachmentID uint) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// releaseAttachmentBlob 公开图片 blob 引用计数-1;最后一个引用删除时回收物理文件
|
||||
func (s *UploadService) releaseAttachmentBlob(att *model.Attachment) error {
|
||||
b, last, err := releaseBlobRef(s.db, att.BlobHash, true)
|
||||
if err != nil || !last {
|
||||
return err
|
||||
}
|
||||
return s.removePublicBlobObject(b, att.URL)
|
||||
}
|
||||
|
||||
// releaseBlobBestEffort 业务记录落库失败时回滚刚加的引用,错误只记日志
|
||||
func (s *UploadService) releaseBlobBestEffort(hash string, public bool, localURL string) {
|
||||
b, last, err := releaseBlobRef(s.db, hash, public)
|
||||
if err != nil {
|
||||
log.Printf("[upload] 回滚 blob 引用失败 hash=%s: %v", hash, err)
|
||||
return
|
||||
}
|
||||
if !last {
|
||||
return
|
||||
}
|
||||
if err := s.removePublicBlobObject(b, localURL); err != nil {
|
||||
log.Printf("[upload] 回滚 blob 物理文件失败 hash=%s: %v", hash, err)
|
||||
}
|
||||
}
|
||||
|
||||
// removePublicBlobObject 引用归零后的物理回收:远程对象失败需上抛(与历史行为一致),
|
||||
// 本地文件失败只记日志(下次同内容上传会自愈覆盖)。
|
||||
func (s *UploadService) removePublicBlobObject(b model.Blob, localURL string) error {
|
||||
if b.ObjectID != "" && s.ops != nil {
|
||||
if e := s.ops.RemoveObject(b.ObjectID); e != nil {
|
||||
return errors.New("记录已删除,远程文件清理未完成,请联系管理员")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if localURL == "" {
|
||||
return nil
|
||||
}
|
||||
abs := filepath.Join(s.dir, filepath.FromSlash(strings.TrimPrefix(localURL, "/uploads/")))
|
||||
if err := os.Remove(abs); err != nil && !os.IsNotExist(err) {
|
||||
log.Printf("[upload] 删除 blob 文件失败 hash=%s path=%s: %v", b.Hash, abs, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *UploadService) WithOperations(o *Operations) { s.ops = o }
|
||||
|
||||
@@ -25,7 +25,7 @@ func newUploadTestService(t *testing.T) (*UploadService, string) {
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.Attachment{}); err != nil {
|
||||
if err := db.AutoMigrate(&model.Attachment{}, &model.Blob{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
@@ -60,7 +60,7 @@ func TestSaveImageTranscodesJPEGToWebP(t *testing.T) {
|
||||
t.Fatalf("encode jpeg: %v", err)
|
||||
}
|
||||
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()))
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage: %v", err)
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func TestSaveImageTranscodesPNGLosslessKeepsAlpha(t *testing.T) {
|
||||
t.Fatalf("encode png: %v", err)
|
||||
}
|
||||
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()))
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage: %v", err)
|
||||
}
|
||||
@@ -133,7 +133,7 @@ func TestSaveImageKeepsGIFAsIs(t *testing.T) {
|
||||
t.Fatalf("encode gif: %v", err)
|
||||
}
|
||||
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()))
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage: %v", err)
|
||||
}
|
||||
@@ -156,7 +156,7 @@ func TestSaveImageKeepsWebPAsIs(t *testing.T) {
|
||||
t.Fatalf("encode webp: %v", err)
|
||||
}
|
||||
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()))
|
||||
att, err := s.SaveImage(1, bytes.NewReader(in.Bytes()), "post")
|
||||
if err != nil {
|
||||
t.Fatalf("SaveImage: %v", err)
|
||||
}
|
||||
|
||||
BIN
docs/images/wechat.png
Normal file
|
After Width: | Height: | Size: 66 KiB |
BIN
docs/images/zfb.png
Normal file
|
After Width: | Height: | Size: 68 KiB |
BIN
docs/images/书库.png
Normal file
|
After Width: | Height: | Size: 325 KiB |
BIN
docs/images/代码片段.png
Normal file
|
After Width: | Height: | Size: 551 KiB |
BIN
docs/images/帖子详情.png
Normal file
|
After Width: | Height: | Size: 395 KiB |
BIN
docs/images/管理后台.png
Normal file
|
After Width: | Height: | Size: 182 KiB |
BIN
docs/images/访问统计.png
Normal file
|
After Width: | Height: | Size: 159 KiB |
BIN
docs/images/首页.png
Normal file
|
After Width: | Height: | Size: 344 KiB |
@@ -9,7 +9,7 @@ import {
|
||||
} from "@/lib/api";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { pageGlyph } from "@/lib/pageGlyph";
|
||||
import {
|
||||
@@ -94,7 +94,7 @@ export default async function AboutIndexPage() {
|
||||
const announcements = overview?.announcements ?? [];
|
||||
const siteLead = settings.site_description?.trim() || undefined;
|
||||
const urlStyle = settings.url_style;
|
||||
const canManagePages = !!me.user && isAdminOrAbove(me.user.role);
|
||||
const canManagePages = !!me.user && hasPerm(me.user, PERMS.PAGES);
|
||||
|
||||
const left = <SiteDocIdentity kind="about" lead={siteLead} />;
|
||||
const right = <SiteDocAnnoNav items={announcements} />;
|
||||
|
||||
@@ -46,6 +46,7 @@ import Modal from "@/components/Modal";
|
||||
import { AdText } from "@/components/AdText";
|
||||
import { formatRelative } from "@/lib/format";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { densitySrcSet, isOwnImage, pickVariantWidth, variantURL } from "@/lib/responsiveImage";
|
||||
|
||||
type StatusFilter = "" | "pending" | "active" | "rejected" | "expired";
|
||||
type SectionId = "overview" | "queue" | "promote" | "sponsors";
|
||||
@@ -882,8 +883,14 @@ function AdCard({
|
||||
{/* 预览缩略 */}
|
||||
<div className="j13-ads-thumb shrink-0" aria-hidden>
|
||||
{ad.kind === "image" && ad.image_url ? (
|
||||
// 88×44 缩略位:本站图走 96/160 密度变体;外链图保持原地址
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={ad.image_url} alt="" className="h-full w-full object-contain" />
|
||||
<img
|
||||
src={isOwnImage(ad.image_url) ? variantURL(ad.image_url, pickVariantWidth(88)) : ad.image_url}
|
||||
srcSet={isOwnImage(ad.image_url) ? densitySrcSet(ad.image_url, 88) : undefined}
|
||||
alt=""
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : ad.kind === "text" && ad.title ? (
|
||||
<div className="flex h-full w-full items-center justify-center p-1.5">
|
||||
<AdText title={ad.title} textColor={ad.text_color} bgColor={ad.bg_color} />
|
||||
@@ -990,8 +997,14 @@ function PaymentEditor({
|
||||
{/* 二维码:点击即上传 */}
|
||||
<label className="j13-ads-qrbox shrink-0 cursor-pointer" title="点击上传/更换收款码">
|
||||
{payment.qr_url ? (
|
||||
// 96×96 收款码位:本站图走 96/160 变体
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={payment.qr_url} alt="" className="h-full w-full object-contain" />
|
||||
<img
|
||||
src={isOwnImage(payment.qr_url) ? variantURL(payment.qr_url, pickVariantWidth(96)) : payment.qr_url}
|
||||
srcSet={isOwnImage(payment.qr_url) ? densitySrcSet(payment.qr_url, 96) : undefined}
|
||||
alt=""
|
||||
className="h-full w-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex flex-col items-center gap-1 text-[11px]" style={{ color: "var(--ink-3)" }}>
|
||||
<Upload size={16} />
|
||||
@@ -1084,8 +1097,14 @@ function SponsorEditor({
|
||||
{/* Logo:点击即上传 */}
|
||||
<label className="j13-ads-logo shrink-0 cursor-pointer" title="点击上传/更换 Logo">
|
||||
{item.logo_url ? (
|
||||
// 120×56 Logo 位:本站图走 160/256 变体
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={item.logo_url} alt="" className="h-full w-full rounded-lg object-contain" />
|
||||
<img
|
||||
src={isOwnImage(item.logo_url) ? variantURL(item.logo_url, pickVariantWidth(120)) : item.logo_url}
|
||||
srcSet={isOwnImage(item.logo_url) ? densitySrcSet(item.logo_url, 120) : undefined}
|
||||
alt=""
|
||||
className="h-full w-full rounded-lg object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="flex flex-col items-center gap-1 text-[11px]" style={{ color: "var(--ink-3)" }}>
|
||||
<Upload size={15} />
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
type SponsorsConfig,
|
||||
} from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -22,7 +22,7 @@ export const metadata: Metadata = {
|
||||
export default async function AdminAdsPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.ADS)) {
|
||||
return <Forbidden text="推广与赞助管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ function DetailsInner() {
|
||||
<div className="w-full sm:w-56">
|
||||
<AdminSearchField
|
||||
value={path}
|
||||
onChange={(v) => { setPath(v); }}
|
||||
onChange={(v) => { setPath(v); resetPage(); }}
|
||||
onSubmit={resetPage}
|
||||
onClear={() => { setPath(""); resetPage(); }}
|
||||
placeholder="路径模糊匹配,回车应用"
|
||||
@@ -148,7 +148,7 @@ function DetailsInner() {
|
||||
<div className="w-full sm:w-48">
|
||||
<AdminSearchField
|
||||
value={ip}
|
||||
onChange={setIp}
|
||||
onChange={(v) => { setIp(v); resetPage(); }}
|
||||
onSubmit={resetPage}
|
||||
onClear={() => { setIp(""); resetPage(); }}
|
||||
placeholder="按 IP 精确筛选"
|
||||
@@ -158,7 +158,7 @@ function DetailsInner() {
|
||||
<div className="w-full sm:w-44">
|
||||
<AdminSearchField
|
||||
value={bot}
|
||||
onChange={setBot}
|
||||
onChange={(v) => { setBot(v); resetPage(); }}
|
||||
onSubmit={resetPage}
|
||||
onClear={() => { setBot(""); resetPage(); }}
|
||||
placeholder="按爬虫名精确筛选"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Suspense } from "react";
|
||||
import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../../../Forbidden";
|
||||
import AnnouncementEditLoader from "./AnnouncementEditLoader";
|
||||
|
||||
@@ -19,7 +19,7 @@ export default async function AdminAnnouncementEditPage({ params }: PageProps) {
|
||||
const { id } = await params;
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.ANNOUNCEMENTS)) {
|
||||
return <Forbidden text="公告管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Suspense } from "react";
|
||||
import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../../Forbidden";
|
||||
import AnnouncementComposeClient from "../AnnouncementComposeClient";
|
||||
|
||||
@@ -14,7 +14,7 @@ export const metadata: Metadata = {
|
||||
export default async function AdminAnnouncementNewPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.ANNOUNCEMENTS)) {
|
||||
return <Forbidden text="公告管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,18 +5,18 @@ import AnnouncementAdmin from "./AnnouncementAdmin";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { fetchAdminAnnouncements, type Announcement } from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "站点公告管理",
|
||||
};
|
||||
|
||||
// 公告管理仅管理员及以上可用(板块管理员无公告权;后端路由另有守卫)
|
||||
// 公告管理:管理员及以上角色自带;超管/站长亦可授予任意账号
|
||||
export default async function AdminAnnouncementsPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.ANNOUNCEMENTS)) {
|
||||
return <Forbidden text="公告管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useEffect, useState } from "react";
|
||||
import Modal from "@/components/Modal";
|
||||
import { apiMyMedia, type MediaAttachment } from "@/lib/api";
|
||||
import { mediaURLFitsBackground, type BgSurface } from "@/lib/bg";
|
||||
import { isOwnImage, variantURL, widthSrcSet } from "@/lib/responsiveImage";
|
||||
|
||||
const SURFACE_LABEL: Record<BgSurface, string> = {
|
||||
site: "前台背景",
|
||||
@@ -101,7 +102,9 @@ export default function BgMediaPicker({
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={item.url}
|
||||
src={isOwnImage(item.url) ? variantURL(item.url, 160) : item.url}
|
||||
srcSet={isOwnImage(item.url) ? widthSrcSet(item.url, [96, 160, 256, 384]) : undefined}
|
||||
sizes="(max-width:520px) 23vw, 96px"
|
||||
alt={`${SURFACE_LABEL[surface]}候选图`}
|
||||
className="w-full h-full object-cover"
|
||||
loading="lazy"
|
||||
|
||||
@@ -42,7 +42,7 @@ import {
|
||||
} from "@/lib/api";
|
||||
import { canModerateAuthor } from "@/lib/roles";
|
||||
import { formatRelative } from "@/lib/format";
|
||||
import { postPath } from "@/lib/urlStyle";
|
||||
import { postPath, commentAnchor } from "@/lib/urlStyle";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { realtime, RT_MODERATION_CHANGED } from "@/lib/realtime";
|
||||
import Avatar from "@/components/Avatar";
|
||||
@@ -692,7 +692,7 @@ export default function ContentAdmin({
|
||||
c.post_title
|
||||
) : (
|
||||
<Link
|
||||
href={`${postPath(urlStyle, c.post_id)}#comment-${c.id}`}
|
||||
href={`${postPath(urlStyle, c.post_id)}${commentAnchor(c.floor, c.is_root, c.id)}`}
|
||||
className="hover:underline"
|
||||
style={{ color: "var(--accent)" }}
|
||||
>
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type FriendLinkStatus,
|
||||
} from "@/lib/api";
|
||||
import { AdminPageHeader, AdminSettingsPage, AdminEmpty } from "@/components/admin";
|
||||
import { densitySrcSet, isOwnImage, pickVariantWidth, variantURL } from "@/lib/responsiveImage";
|
||||
|
||||
interface Props {
|
||||
initialLinks: FriendLink[];
|
||||
@@ -237,9 +238,11 @@ export default function FriendLinksAdmin({ initialLinks, initError }: Props) {
|
||||
style={{ borderTop: "1px solid var(--line)" }}
|
||||
>
|
||||
{l.logo_url ? (
|
||||
// 36px 位:本站图走 48/96 变体;外链保持原样
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={l.logo_url}
|
||||
src={isOwnImage(l.logo_url) ? variantURL(l.logo_url, pickVariantWidth(36)) : l.logo_url}
|
||||
srcSet={isOwnImage(l.logo_url) ? densitySrcSet(l.logo_url, 36) : undefined}
|
||||
alt=""
|
||||
width={36}
|
||||
height={36}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { redirect } from "next/navigation";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { authCookieHeader, REFRESH_COOKIE, CSRF_COOKIE, TOKEN_COOKIE } from "@/lib/cookies";
|
||||
import { getMeCached, getPublicSettingsCached } from "@/lib/serverData";
|
||||
import { canAccessAdminMessages, isStaff } from "@/lib/roles";
|
||||
import { canAccessAdminMessages, hasAnyChannelPerm, isStaff } from "@/lib/roles";
|
||||
import AdminShell from "@/components/admin/AdminShell";
|
||||
import AdminSessionRecover from "./AdminSessionRecover";
|
||||
|
||||
@@ -15,7 +15,7 @@ export const metadata: Metadata = {
|
||||
};
|
||||
|
||||
// 权限以 Go 端为唯一判定;此处仅决定管理界面是否直出。
|
||||
// 允许:管理角色,或仅有消息管理/群管权限的用户(仅消息菜单可见)。
|
||||
// 允许:管理角色 / 消息管理/群管权限 / 任一渠道权限(公告/单页/书库/广告)。
|
||||
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
|
||||
const cookieStore = await cookies();
|
||||
const cookie = authCookieHeader(cookieStore);
|
||||
@@ -24,7 +24,8 @@ export default async function AdminLayout({ children }: { children: React.ReactN
|
||||
const theme = cookieStore.get("j13-theme")?.value === "dark" ? "dark" : "light";
|
||||
|
||||
const allowed =
|
||||
!!me.user && (isStaff(me.user.role) || canAccessAdminMessages(me.user));
|
||||
!!me.user &&
|
||||
(isStaff(me.user.role) || canAccessAdminMessages(me.user) || hasAnyChannelPerm(me.user));
|
||||
|
||||
if (!allowed || !me.user) {
|
||||
// 已登录但无后台权限:保留提示卡片
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useMemo, useRef, useState, type ChangeEvent } from "react";
|
||||
import {
|
||||
BookOpen,
|
||||
Download,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
apiAdminCreateLibraryDoc,
|
||||
apiAdminDeleteLibraryDoc,
|
||||
apiAdminDeleteLibraryFile,
|
||||
apiAdminImportLibraryZip,
|
||||
apiAdminListLibraryDocs,
|
||||
apiAdminPurgeLibraryDoc,
|
||||
apiAdminUpdateLibraryDoc,
|
||||
@@ -25,17 +26,20 @@ import {
|
||||
apiUploadPostImage,
|
||||
type LibraryDoc,
|
||||
type LibraryFileItem,
|
||||
type LibraryImportReport,
|
||||
type LibraryInput,
|
||||
} from "@/lib/api";
|
||||
import { formatDateTime, formatRelative } from "@/lib/format";
|
||||
import { libraryDocPath } from "@/lib/urlStyle";
|
||||
import { libraryDocPath, userPath } from "@/lib/urlStyle";
|
||||
import { useUrlStyle } from "@/components/SiteBrandProvider";
|
||||
import { toast } from "@/lib/toast";
|
||||
import ConfirmDialog from "@/components/ConfirmDialog";
|
||||
import Avatar from "@/components/Avatar";
|
||||
import MarkdownEditor from "@/components/MarkdownEditor";
|
||||
import { AdminEmpty, AdminField, AdminPageHeader, AdminStatusChip, AdminSwitch } from "@/components/admin";
|
||||
import LibrarySectionsPanel from "./LibrarySectionsPanel";
|
||||
import LibraryCoverPicker from "./LibraryCoverPicker";
|
||||
import { densitySrcSet, isOwnImage, pickVariantWidth, variantURL } from "@/lib/responsiveImage";
|
||||
|
||||
// 与后端 libraryAllowedExts 保持一致;前端先拦一道,后端仍会校验
|
||||
const ALLOWED_EXTS = new Set([
|
||||
@@ -59,9 +63,12 @@ function formatSize(n: number): string {
|
||||
|
||||
interface DocForm {
|
||||
title: string;
|
||||
author: string;
|
||||
slug: string;
|
||||
description: string;
|
||||
cover_url: string;
|
||||
cover_width: number;
|
||||
cover_height: number;
|
||||
published: boolean;
|
||||
sort_order: number;
|
||||
entries_auto: boolean;
|
||||
@@ -69,9 +76,12 @@ interface DocForm {
|
||||
|
||||
const EMPTY_FORM: DocForm = {
|
||||
title: "",
|
||||
author: "",
|
||||
slug: "",
|
||||
description: "",
|
||||
cover_url: "",
|
||||
cover_width: 0,
|
||||
cover_height: 0,
|
||||
published: false,
|
||||
sort_order: 0,
|
||||
entries_auto: false,
|
||||
@@ -80,9 +90,12 @@ const EMPTY_FORM: DocForm = {
|
||||
function formOfDoc(d: LibraryDoc): DocForm {
|
||||
return {
|
||||
title: d.title,
|
||||
author: d.author ?? "",
|
||||
slug: d.slug,
|
||||
description: d.description ?? "",
|
||||
cover_url: d.cover_url ?? "",
|
||||
cover_width: d.cover_width ?? 0,
|
||||
cover_height: d.cover_height ?? 0,
|
||||
published: d.published,
|
||||
sort_order: d.sort_order,
|
||||
entries_auto: d.entries_auto ?? false,
|
||||
@@ -145,6 +158,13 @@ export default function LibraryAdmin({
|
||||
const [fileDeleteTarget, setFileDeleteTarget] = useState<LibraryFileItem | null>(null);
|
||||
const [fileDeleteBusy, setFileDeleteBusy] = useState(false);
|
||||
|
||||
// 书库导入恢复(上传导出 ZIP)
|
||||
const importInputRef = useRef<HTMLInputElement>(null);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [importReport, setImportReport] = useState<LibraryImportReport | null>(null);
|
||||
// create 模式遇到 conflict 时保留 File,供确认后 overwrite 重传
|
||||
const [importOverwrite, setImportOverwrite] = useState<{ file: File; count: number } | null>(null);
|
||||
|
||||
// 条目删除(软删)与彻底删除
|
||||
const [docDeleteTarget, setDocDeleteTarget] = useState<LibraryDoc | null>(null);
|
||||
const [docDeleteBusy, setDocDeleteBusy] = useState(false);
|
||||
@@ -170,6 +190,34 @@ export default function LibraryAdmin({
|
||||
}
|
||||
}
|
||||
|
||||
async function runImport(file: File, mode: "create" | "overwrite") {
|
||||
setImporting(true);
|
||||
setImportReport(null);
|
||||
try {
|
||||
const rep = await apiAdminImportLibraryZip(file, mode);
|
||||
setImportReport(rep);
|
||||
const okN = rep.imported.length;
|
||||
const failN = rep.failed.length;
|
||||
if (okN > 0) toast(`成功导入 ${okN} 本书${failN ? `,${failN} 本未导入` : ""}`, "ok");
|
||||
else toast("没有书籍被导入,请查看失败明细", "error");
|
||||
await reload();
|
||||
if (mode === "create") {
|
||||
const conflicts = rep.failed.filter((f) => f.reason === "conflict").length;
|
||||
if (conflicts > 0) setImportOverwrite({ file, count: conflicts });
|
||||
}
|
||||
} catch (e) {
|
||||
toast(e instanceof Error ? e.message : "导入失败");
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function onPickImportFile(e: ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = ""; // 允许重选同一文件
|
||||
if (file) void runImport(file, "create");
|
||||
}
|
||||
|
||||
function openNew() {
|
||||
setForm(EMPTY_FORM);
|
||||
setSnapshot(JSON.stringify(EMPTY_FORM));
|
||||
@@ -221,8 +269,11 @@ export default function LibraryAdmin({
|
||||
const input: LibraryInput = {
|
||||
slug,
|
||||
title,
|
||||
author: form.author.trim(),
|
||||
description: form.description,
|
||||
cover_url: form.cover_url.trim(),
|
||||
cover_width: form.cover_width,
|
||||
cover_height: form.cover_height,
|
||||
published: form.published,
|
||||
sort_order: form.sort_order,
|
||||
entries_auto: form.entries_auto,
|
||||
@@ -250,9 +301,13 @@ export default function LibraryAdmin({
|
||||
if (!file) return;
|
||||
setCoverBusy(true);
|
||||
try {
|
||||
const res = await apiUploadPostImage(file);
|
||||
const res = await apiUploadPostImage(file, undefined, "library_cover");
|
||||
if (res.url) {
|
||||
patchForm({ cover_url: res.url });
|
||||
patchForm({
|
||||
cover_url: res.url,
|
||||
cover_width: res.attachment?.width ?? 0,
|
||||
cover_height: res.attachment?.height ?? 0,
|
||||
});
|
||||
} else {
|
||||
setFormError(res.error || "封面上传失败");
|
||||
}
|
||||
@@ -267,8 +322,8 @@ export default function LibraryAdmin({
|
||||
async function pickCoverFromMedia(attachmentId: number) {
|
||||
setCoverBusy(true);
|
||||
try {
|
||||
const url = await apiLibraryCoverFromMedia(attachmentId);
|
||||
patchForm({ cover_url: url });
|
||||
const { url, width, height } = await apiLibraryCoverFromMedia(attachmentId);
|
||||
patchForm({ cover_url: url, cover_width: width, cover_height: height });
|
||||
} catch (e) {
|
||||
setFormError(e instanceof Error ? e.message : "选用图库图片失败");
|
||||
} finally {
|
||||
@@ -374,17 +429,103 @@ export default function LibraryAdmin({
|
||||
title="书库管理"
|
||||
description="书籍、文档与页面作品。书籍由介绍、目录与章节正文组成,像书一样阅读;附件仅提供下载分发。"
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => guardNav(openNew)}
|
||||
disabled={saving}
|
||||
>
|
||||
<Plus size={15} /> 新建条目
|
||||
</button>
|
||||
<>
|
||||
<a
|
||||
href="/api/admin/library/export"
|
||||
className="btn btn-ghost"
|
||||
title="把全部书籍打包为 ZIP(介绍、章节、附件与封面),用于迁移或备份"
|
||||
>
|
||||
<Download size={15} aria-hidden />
|
||||
导出全部
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost"
|
||||
onClick={() => importInputRef.current?.click()}
|
||||
disabled={importing}
|
||||
title="上传导出的 ZIP 备份包,恢复书籍(介绍、章节、附件与封面)"
|
||||
>
|
||||
{importing ? (
|
||||
<Loader2 size={15} className="animate-spin" aria-hidden />
|
||||
) : (
|
||||
<Upload size={15} aria-hidden />
|
||||
)}
|
||||
{importing ? "导入中…" : "导入恢复"}
|
||||
</button>
|
||||
<input
|
||||
ref={importInputRef}
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
className="hidden"
|
||||
onChange={onPickImportFile}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={() => guardNav(openNew)}
|
||||
disabled={saving}
|
||||
>
|
||||
<Plus size={15} /> 新建条目
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{importReport ? (
|
||||
<div
|
||||
className="panel mx-3.5 sm:mx-4 my-3 px-4 py-3 text-[13px]"
|
||||
role="status"
|
||||
style={{ borderColor: "var(--line)" }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<strong style={{ color: "var(--ink)" }}>
|
||||
导入完成:成功 {importReport.imported.length} 本
|
||||
(新建 {importReport.imported.filter((i) => i.action === "created").length} / 覆盖{" "}
|
||||
{importReport.imported.filter((i) => i.action === "overwritten").length}),失败{" "}
|
||||
{importReport.failed.length} 本
|
||||
</strong>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-auto btn btn-ghost"
|
||||
style={{ padding: "2px 6px" }}
|
||||
onClick={() => setImportReport(null)}
|
||||
aria-label="关闭导入结果"
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</button>
|
||||
</div>
|
||||
{importReport.failed.length > 0 ? (
|
||||
<ul className="mt-2 flex flex-col gap-1">
|
||||
{importReport.failed.map((f, i) => (
|
||||
<li key={`${f.slug}-${i}`} className="meta flex flex-wrap items-baseline gap-x-2">
|
||||
<span style={{ color: "var(--ink-2)" }}>
|
||||
{f.title || f.slug}
|
||||
{f.slug ? `(${f.slug})` : ""}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
color:
|
||||
f.reason === "conflict" || f.reason === "deleted"
|
||||
? "var(--warn, #b45309)"
|
||||
: "var(--danger, #b91c1c)",
|
||||
}}
|
||||
>
|
||||
{f.reason === "conflict"
|
||||
? "同名书籍已存在,可覆盖导入"
|
||||
: f.reason === "deleted"
|
||||
? "地址被已删除条目占用,需先彻底删除"
|
||||
: f.reason === "invalid"
|
||||
? "备份数据不受支持"
|
||||
: "导入失败"}
|
||||
</span>
|
||||
<span>{f.error}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div
|
||||
className="admin-library-split"
|
||||
data-view={editorOpen ? "editor" : "list"}
|
||||
@@ -435,9 +576,11 @@ export default function LibraryAdmin({
|
||||
}}
|
||||
>
|
||||
{d.cover_url ? (
|
||||
// 36px 封面位:本站图走 48/96 变体
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={d.cover_url}
|
||||
src={isOwnImage(d.cover_url) ? variantURL(d.cover_url, pickVariantWidth(36)) : d.cover_url}
|
||||
srcSet={isOwnImage(d.cover_url) ? densitySrcSet(d.cover_url, 36) : undefined}
|
||||
alt=""
|
||||
className="w-9 h-9 rounded-lg object-cover shrink-0"
|
||||
style={{ border: "1px solid var(--line)" }}
|
||||
@@ -560,6 +703,16 @@ export default function LibraryAdmin({
|
||||
? `${editingDoc.sections?.length ?? 0} 章节 · ${editingDoc.files?.length ?? 0} 附件`
|
||||
: ""}
|
||||
</span>
|
||||
{typeof editingId === "number" ? (
|
||||
<a
|
||||
href={`/api/admin/library/docs/${editingId}/export`}
|
||||
className="btn btn-line btn-sm shrink-0"
|
||||
title="导出本书为 ZIP(介绍、章节、附件与本地封面),用于迁移或备份"
|
||||
>
|
||||
<Download size={13} aria-hidden />
|
||||
导出备份
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* 书籍信息 tab(两个 tab 均保持挂载,避免章节编辑状态丢失)。
|
||||
@@ -586,6 +739,15 @@ export default function LibraryAdmin({
|
||||
className="admin-doc-title"
|
||||
/>
|
||||
|
||||
<AdminField
|
||||
id="lib-author"
|
||||
label="作者"
|
||||
maxLength={100}
|
||||
value={form.author}
|
||||
onChange={(author) => patchForm({ author })}
|
||||
placeholder="作者或编著者,多位可用逗号分隔(可选)"
|
||||
/>
|
||||
|
||||
<div className="admin-doc-field">
|
||||
<label className="admin-doc-label" htmlFor="lib-slug">
|
||||
访问地址
|
||||
@@ -628,6 +790,7 @@ export default function LibraryAdmin({
|
||||
placeholder="条目介绍,支持 Markdown…"
|
||||
rows={12}
|
||||
ariaLabel="条目介绍"
|
||||
uploadSource="library_content"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -636,56 +799,58 @@ export default function LibraryAdmin({
|
||||
<aside className="flex flex-col gap-4 lg:min-h-0">
|
||||
<div className="admin-doc-field">
|
||||
<p className="admin-doc-label">封面(可选)</p>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div className="flex flex-col gap-2">
|
||||
{form.cover_url ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={form.cover_url}
|
||||
src={isOwnImage(form.cover_url) ? variantURL(form.cover_url, 256) : form.cover_url}
|
||||
alt="封面预览"
|
||||
className="w-12 h-12 rounded-lg object-cover shrink-0"
|
||||
className="w-full h-32 rounded-xl object-cover"
|
||||
style={{ border: "1px solid var(--line)" }}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className="w-12 h-12 rounded-lg flex items-center justify-center shrink-0"
|
||||
className="w-full h-32 rounded-xl flex flex-col items-center justify-center gap-1.5"
|
||||
style={{ border: "1px dashed var(--control-border)" }}
|
||||
aria-label="上传封面"
|
||||
onClick={() => coverInputRef.current?.click()}
|
||||
>
|
||||
<ImagePlus size={16} style={{ color: "var(--ink-3)" }} aria-hidden />
|
||||
<ImagePlus size={20} style={{ color: "var(--ink-3)" }} aria-hidden />
|
||||
<span className="text-[11.5px]" style={{ color: "var(--ink-3)" }}>
|
||||
点击上传封面
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm flex-1"
|
||||
disabled={coverBusy}
|
||||
onClick={() => coverInputRef.current?.click()}
|
||||
>
|
||||
{coverBusy ? (
|
||||
<Loader2 size={13} className="animate-spin" aria-hidden />
|
||||
) : (
|
||||
<ImagePlus size={13} aria-hidden />
|
||||
)}
|
||||
{form.cover_url ? "更换" : "上传"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm flex-1"
|
||||
disabled={coverBusy}
|
||||
onClick={() => setCoverPickerOpen(true)}
|
||||
>
|
||||
<Images size={13} aria-hidden />
|
||||
图库
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm"
|
||||
disabled={coverBusy}
|
||||
onClick={() => coverInputRef.current?.click()}
|
||||
>
|
||||
{coverBusy ? (
|
||||
<Loader2 size={13} className="animate-spin" aria-hidden />
|
||||
) : (
|
||||
<ImagePlus size={13} aria-hidden />
|
||||
)}
|
||||
{form.cover_url ? "更换" : "上传"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm"
|
||||
disabled={coverBusy}
|
||||
onClick={() => setCoverPickerOpen(true)}
|
||||
>
|
||||
<Images size={13} aria-hidden />
|
||||
图库
|
||||
</button>
|
||||
{form.cover_url ? (
|
||||
<button
|
||||
type="button"
|
||||
className="admin-doc-textbtn"
|
||||
onClick={() => patchForm({ cover_url: "" })}
|
||||
className="admin-doc-textbtn ml-auto"
|
||||
style={{ minHeight: 0, minWidth: 0, padding: "1px 6px", fontSize: 12 }}
|
||||
onClick={() => patchForm({ cover_url: "", cover_width: 0, cover_height: 0 })}
|
||||
>
|
||||
移除
|
||||
</button>
|
||||
@@ -749,6 +914,30 @@ export default function LibraryAdmin({
|
||||
<p className="admin-doc-hint">数字越小越靠前。</p>
|
||||
</div>
|
||||
|
||||
{typeof editingId === "number" && editingDoc?.creator ? (
|
||||
<div className="admin-doc-field">
|
||||
<p className="admin-doc-label">创建者</p>
|
||||
<a
|
||||
href={userPath(urlStyle, editingDoc.creator.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 text-[13px] font-medium max-w-full"
|
||||
style={{ color: "var(--ink)" }}
|
||||
title={`@${editingDoc.creator.username}`}
|
||||
>
|
||||
<Avatar
|
||||
size={22}
|
||||
name={editingDoc.creator.nickname || editingDoc.creator.username}
|
||||
src={editingDoc.creator.avatar}
|
||||
/>
|
||||
<span className="truncate">
|
||||
{editingDoc.creator.nickname || editingDoc.creator.username}
|
||||
</span>
|
||||
</a>
|
||||
<p className="admin-doc-hint">条目创建后归属不变。</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* 附件管理:长列表列内滚动 */}
|
||||
<div className="admin-doc-field flex flex-col lg:flex-1 lg:min-h-0">
|
||||
<p className="admin-doc-label shrink-0">
|
||||
@@ -956,6 +1145,27 @@ export default function LibraryAdmin({
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* 导入遇到同名书籍:确认后覆盖重传(保留同一 File) */}
|
||||
<ConfirmDialog
|
||||
open={!!importOverwrite}
|
||||
title="覆盖导入同名书籍?"
|
||||
message={
|
||||
importOverwrite
|
||||
? `备份包中有 ${importOverwrite.count} 本书的地址已被现有书籍占用。选择覆盖将用备份包整体替换这些书籍的介绍、章节、附件与封面,现有内容不可恢复;其余书籍正常新建。`
|
||||
: ""
|
||||
}
|
||||
danger
|
||||
busy={importing}
|
||||
confirmLabel="覆盖导入"
|
||||
cancelLabel="保留现有"
|
||||
onCancel={() => !importing && setImportOverwrite(null)}
|
||||
onConfirm={() => {
|
||||
const pending = importOverwrite;
|
||||
setImportOverwrite(null);
|
||||
if (pending) void runImport(pending.file, "overwrite");
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 未保存关闭/切换确认 */}
|
||||
<ConfirmDialog
|
||||
open={!!pendingNav}
|
||||
|
||||
@@ -4,8 +4,35 @@ import { Images, Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import Modal from "@/components/Modal";
|
||||
import { apiMyMedia, type MediaAttachment } from "@/lib/api";
|
||||
import { isOwnImage, variantURL, widthSrcSet } from "@/lib/responsiveImage";
|
||||
|
||||
/** 书籍封面图库选择弹窗:列出本人媒体库图片,选中后由父组件复制一份作封面素材 */
|
||||
/** 来源标签映射 */
|
||||
const SOURCE_LABELS: Record<string, string> = {
|
||||
library_cover: "书籍封面",
|
||||
library_content: "书籍内容",
|
||||
post: "帖子插图",
|
||||
};
|
||||
|
||||
function sourceLabel(source?: string): string {
|
||||
return SOURCE_LABELS[source || "post"] || source || "帖子插图";
|
||||
}
|
||||
|
||||
/** 按来源分组(library_cover 优先,其次 library_content,最后 post/其他) */
|
||||
function groupBySource(items: MediaAttachment[]): [string, MediaAttachment[]][] {
|
||||
const groups = new Map<string, MediaAttachment[]>();
|
||||
for (const item of items) {
|
||||
const key = item.source || "post";
|
||||
if (!groups.has(key)) groups.set(key, []);
|
||||
groups.get(key)!.push(item);
|
||||
}
|
||||
// 按优先级排序
|
||||
const order = ["library_cover", "library_content", "post"];
|
||||
return Array.from(groups.entries()).sort(
|
||||
([a], [b]) => order.indexOf(a) - order.indexOf(b)
|
||||
);
|
||||
}
|
||||
|
||||
/** 书籍封面图库选择弹窗:列出本人媒体库图片,按来源分组 */
|
||||
export default function LibraryCoverPicker({
|
||||
open,
|
||||
onClose,
|
||||
@@ -45,13 +72,15 @@ export default function LibraryCoverPicker({
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const groups = groupBySource(items);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title="从图库选择封面"
|
||||
description="选择后会复制一份作为封面素材,之后删除原图不影响封面。"
|
||||
description="已选作封面的图片会单独分组,再次选择直接复用。"
|
||||
onClose={onClose}
|
||||
maxWidthClass="max-w-lg"
|
||||
maxWidthClass="max-w-2xl"
|
||||
dismissOnOverlay
|
||||
>
|
||||
{loading ? (
|
||||
@@ -67,28 +96,52 @@ export default function LibraryCoverPicker({
|
||||
图库还没有图片。上传封面或发帖插图后,会自动出现在这里。
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-4 sm:grid-cols-5 gap-2 max-h-[46vh] overflow-y-auto">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onPick(item);
|
||||
onClose();
|
||||
}}
|
||||
className="relative group aspect-square rounded-xl overflow-hidden"
|
||||
style={{ boxShadow: "0 0 0 1px var(--line)", background: "var(--panel-2)" }}
|
||||
data-tip="复制一份用作封面"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={item.url} alt="图库候选封面" className="w-full h-full object-contain" loading="lazy" />
|
||||
<span
|
||||
className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100"
|
||||
style={{ background: "color-mix(in srgb, var(--ink) 40%, transparent)", color: "#fff" }}
|
||||
<div className="flex flex-col gap-5 max-h-[60vh] overflow-y-auto">
|
||||
{groups.map(([source, groupItems]) => (
|
||||
<section key={source}>
|
||||
<h4
|
||||
className="text-[11.5px] font-bold tracking-wide uppercase mb-2 px-0.5"
|
||||
style={{ color: "var(--ink-3)" }}
|
||||
>
|
||||
<Images size={14} />
|
||||
</span>
|
||||
</button>
|
||||
{sourceLabel(source)}
|
||||
<span className="ml-1.5 font-normal opacity-70">({groupItems.length})</span>
|
||||
</h4>
|
||||
<div className="grid grid-cols-4 sm:grid-cols-5 gap-2">
|
||||
{groupItems.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onPick(item);
|
||||
onClose();
|
||||
}}
|
||||
className="relative group aspect-square rounded-xl overflow-hidden"
|
||||
style={{ boxShadow: "0 0 0 1px var(--line)", background: "var(--panel-2)" }}
|
||||
data-tip={
|
||||
item.source === "library_cover"
|
||||
? "已作封面,点击直接复用"
|
||||
: "复制一份用作封面"
|
||||
}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={isOwnImage(item.url) ? variantURL(item.url, 160) : item.url}
|
||||
srcSet={isOwnImage(item.url) ? widthSrcSet(item.url, [96, 160, 256, 384]) : undefined}
|
||||
sizes="(max-width:520px) 23vw, 96px"
|
||||
alt="图库候选封面"
|
||||
className="w-full h-full object-contain"
|
||||
loading="lazy"
|
||||
/>
|
||||
<span
|
||||
className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100"
|
||||
style={{ background: "color-mix(in srgb, var(--ink) 40%, transparent)", color: "#fff" }}
|
||||
>
|
||||
<Images size={14} />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -410,6 +410,7 @@ export default function LibrarySectionsPanel({
|
||||
placeholder="本章正文,支持 Markdown…"
|
||||
rows={16}
|
||||
ariaLabel="章节正文"
|
||||
uploadSource="library_content"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import LibraryAdmin from "./LibraryAdmin";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { fetchAdminLibraryDocs, type LibraryDoc } from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -15,7 +15,7 @@ export const metadata: Metadata = {
|
||||
export default async function AdminLibraryPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.LIBRARY)) {
|
||||
return <Forbidden text="书库管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Images, Copy, ExternalLink, Eye, Check } from "lucide-react";
|
||||
import Modal from "@/components/Modal";
|
||||
import AdminEmpty from "@/components/admin/AdminEmpty";
|
||||
import type { MediaLibraryItem } from "@/lib/api";
|
||||
import { isOwnImage, variantURL, widthSrcSet } from "@/lib/responsiveImage";
|
||||
|
||||
function formatBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
@@ -24,10 +25,11 @@ function formatDims(item: MediaLibraryItem): string {
|
||||
return "—";
|
||||
}
|
||||
|
||||
/** 网格缩略图:本地图走服务端缩略接口(磁盘缓存),远程对象直连原图(头像类本身小) */
|
||||
/** 网格缩略图:本站图走统一变体端点(磁盘缓存,256 档);非本站图原样返回 */
|
||||
function thumbSrc(item: MediaLibraryItem): string {
|
||||
if (item.url.startsWith("/uploads/")) {
|
||||
return `/api/admin/media-library/thumb?u=${encodeURIComponent(item.url)}`;
|
||||
// 网格缩略走统一变体端点(256 档);非本站图原样返回
|
||||
if (isOwnImage(item.url)) {
|
||||
return variantURL(item.url, 256);
|
||||
}
|
||||
return item.url;
|
||||
}
|
||||
@@ -143,6 +145,8 @@ export default function MediaLibrary({
|
||||
<span className="block relative aspect-square overflow-hidden">
|
||||
<img
|
||||
src={thumbSrc(item)}
|
||||
srcSet={isOwnImage(item.url) ? widthSrcSet(item.url, [160, 256, 384, 512]) : undefined}
|
||||
sizes="(min-width:1280px) 16vw, (min-width:1024px) 25vw, (min-width:640px) 33vw, 50vw"
|
||||
alt={item.name}
|
||||
loading="lazy"
|
||||
className="absolute inset-0 w-full h-full object-cover"
|
||||
@@ -175,7 +179,8 @@ export default function MediaLibrary({
|
||||
<Modal
|
||||
open={active !== null}
|
||||
onClose={() => setActive(null)}
|
||||
title={active?.name ?? ""}
|
||||
title={<span className="break-all">{active?.name ?? ""}</span>}
|
||||
ariaLabel={active?.name ?? ""}
|
||||
description={active ? `${active.category_name}${active.uploader ? ` · 上传者 ${active.uploader}` : ""}` : undefined}
|
||||
maxWidthClass="max-w-2xl"
|
||||
dismissOnOverlay
|
||||
@@ -214,6 +219,14 @@ export default function MediaLibrary({
|
||||
["格式", active.mime],
|
||||
["上传者", active.uploader || "—"],
|
||||
["时间", formatTime(active.uploaded_at)],
|
||||
...(active.ref_count && active.ref_count > 1
|
||||
? [
|
||||
[
|
||||
"引用",
|
||||
`${active.ref_count} 次上传 · 去重节省 ${formatBytes(active.size * (active.ref_count - 1))}`,
|
||||
],
|
||||
]
|
||||
: []),
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="flex items-baseline gap-2 min-w-0">
|
||||
<dt className="meta shrink-0 w-11 text-right">{k}</dt>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Suspense } from "react";
|
||||
import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../../../Forbidden";
|
||||
import PageEditLoader from "./PageEditLoader";
|
||||
|
||||
@@ -19,7 +19,7 @@ export default async function AdminPageEditPage({ params }: PageProps) {
|
||||
const { id } = await params;
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.PAGES)) {
|
||||
return <Forbidden text="单页管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Suspense } from "react";
|
||||
import { cookies } from "next/headers";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../../Forbidden";
|
||||
import PageComposeClient from "../PageComposeClient";
|
||||
|
||||
@@ -14,7 +14,7 @@ export const metadata: Metadata = {
|
||||
export default async function AdminPageNewPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.PAGES)) {
|
||||
return <Forbidden text="单页管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import PagesAdmin from "./PagesAdmin";
|
||||
import { authCookieHeader } from "@/lib/cookies";
|
||||
import { fetchAdminSitePages, type SitePage } from "@/lib/api";
|
||||
import { getMeCached } from "@/lib/serverData";
|
||||
import { isAdminOrAbove } from "@/lib/roles";
|
||||
import { hasPerm, PERMS } from "@/lib/roles";
|
||||
import Forbidden from "../Forbidden";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -15,7 +15,7 @@ export const metadata: Metadata = {
|
||||
export default async function AdminPagesPage() {
|
||||
const cookie = authCookieHeader(await cookies());
|
||||
const me = await getMeCached(cookie || undefined);
|
||||
if (!me.user || !isAdminOrAbove(me.user.role)) {
|
||||
if (!me.user || !hasPerm(me.user, PERMS.PAGES)) {
|
||||
return <Forbidden text="单页管理仅管理员及以上角色可操作。" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { X } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { AdminField, AdminSettingsActions, AdminSettingsGroup } from "@/components/admin";
|
||||
import { AdminField, AdminSettingsActions, AdminSettingsGroup, AdminSwitch } from "@/components/admin";
|
||||
import { apiUpdateSiteSettings, apiOperations, type PublicSettings } from "@/lib/api";
|
||||
import { BRAND_LIMITS, runeCount, siteDocumentTitle } from "@/lib/brand";
|
||||
import { toast } from "@/lib/toast";
|
||||
@@ -25,6 +25,7 @@ export default function BasicIdentityPanel({
|
||||
}, []);
|
||||
const [wordmark, setWordmark] = useState(initial.site_wordmark);
|
||||
const [slogan, setSlogan] = useState(initial.site_slogan);
|
||||
const [sloganVisible, setSloganVisible] = useState(initial.brand_slogan_visible);
|
||||
const [desc, setDesc] = useState(initial.site_description);
|
||||
const [keywords, setKeywords] = useState<string[]>(initial.site_keywords);
|
||||
const [kwInput, setKwInput] = useState("");
|
||||
@@ -32,6 +33,7 @@ export default function BasicIdentityPanel({
|
||||
name: initial.site_name,
|
||||
wordmark: initial.site_wordmark,
|
||||
slogan: initial.site_slogan,
|
||||
sloganVisible: initial.brand_slogan_visible,
|
||||
desc: initial.site_description,
|
||||
keywords: initial.site_keywords,
|
||||
});
|
||||
@@ -44,6 +46,7 @@ export default function BasicIdentityPanel({
|
||||
name.trim() !== saved.name ||
|
||||
wordmark.trim() !== saved.wordmark ||
|
||||
slogan.trim() !== saved.slogan ||
|
||||
sloganVisible !== saved.sloganVisible ||
|
||||
desc.trim() !== saved.desc ||
|
||||
JSON.stringify(keywords) !== JSON.stringify(saved.keywords);
|
||||
|
||||
@@ -85,6 +88,7 @@ export default function BasicIdentityPanel({
|
||||
setName(saved.name);
|
||||
setWordmark(saved.wordmark);
|
||||
setSlogan(saved.slogan);
|
||||
setSloganVisible(saved.sloganVisible);
|
||||
setDesc(saved.desc);
|
||||
setKeywords([...saved.keywords]);
|
||||
setKwInput("");
|
||||
@@ -98,6 +102,7 @@ export default function BasicIdentityPanel({
|
||||
name: name.trim(),
|
||||
wordmark: wordmark.trim(),
|
||||
slogan: slogan.trim(),
|
||||
sloganVisible,
|
||||
desc: desc.trim(),
|
||||
keywords: [...keywords],
|
||||
};
|
||||
@@ -115,6 +120,7 @@ export default function BasicIdentityPanel({
|
||||
site_name: snap.name,
|
||||
site_wordmark: snap.wordmark,
|
||||
site_slogan: snap.slogan,
|
||||
brand_slogan_visible: snap.sloganVisible,
|
||||
site_description: snap.desc,
|
||||
site_keywords: snap.keywords,
|
||||
});
|
||||
@@ -123,12 +129,14 @@ export default function BasicIdentityPanel({
|
||||
name: res.site_name,
|
||||
wordmark: res.site_wordmark,
|
||||
slogan: res.site_slogan,
|
||||
sloganVisible: res.brand_slogan_visible,
|
||||
desc: res.site_description,
|
||||
keywords: res.site_keywords,
|
||||
});
|
||||
setName((v) => (v.trim() === snap.name ? res.site_name : v));
|
||||
setWordmark((v) => (v.trim() === snap.wordmark ? res.site_wordmark : v));
|
||||
setSlogan((v) => (v.trim() === snap.slogan ? res.site_slogan : v));
|
||||
setSloganVisible((v) => (v === snap.sloganVisible ? res.brand_slogan_visible : v));
|
||||
setDesc((v) => (v.trim() === snap.desc ? res.site_description : v));
|
||||
setKeywords((prev) =>
|
||||
JSON.stringify(prev) === JSON.stringify(snap.keywords) ? res.site_keywords : prev,
|
||||
@@ -199,18 +207,49 @@ export default function BasicIdentityPanel({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AdminField
|
||||
id="site-slogan"
|
||||
label="标语"
|
||||
className="admin-identity-field"
|
||||
maxLength={BRAND_LIMITS.slogan}
|
||||
value={slogan}
|
||||
onChange={(v) => {
|
||||
setSlogan(v);
|
||||
clearSaveError();
|
||||
}}
|
||||
placeholder="技术分享与讨论"
|
||||
/>
|
||||
<div className="admin-identity-field">
|
||||
<div className="admin-field-head">
|
||||
<label className="field-label" htmlFor="site-slogan">
|
||||
标语
|
||||
</label>
|
||||
<span className="admin-field-count" aria-hidden>
|
||||
{slogan.length}/{BRAND_LIMITS.slogan}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className="flex items-center gap-2 mb-2"
|
||||
title={slogan.trim() ? "在页眉站名下方显示副标题" : "先填写标语后可开启"}
|
||||
>
|
||||
<AdminSwitch
|
||||
checked={sloganVisible}
|
||||
disabled={!slogan.trim()}
|
||||
onChange={() => {
|
||||
setSloganVisible((v) => !v);
|
||||
clearSaveError();
|
||||
}}
|
||||
label="页眉显示标语"
|
||||
/>
|
||||
<span
|
||||
className="text-[12px]"
|
||||
style={{ color: slogan.trim() ? "var(--ink-2)" : "var(--ink-3)" }}
|
||||
>
|
||||
页眉显示标语
|
||||
</span>
|
||||
</div>
|
||||
<div className="admin-field-shell">
|
||||
<input
|
||||
id="site-slogan"
|
||||
className="admin-field-input"
|
||||
maxLength={BRAND_LIMITS.slogan}
|
||||
value={slogan}
|
||||
onChange={(e) => {
|
||||
setSlogan(e.target.value);
|
||||
clearSaveError();
|
||||
}}
|
||||
placeholder="技术分享与讨论"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="admin-identity-title-preview" aria-live="polite">
|
||||
浏览器标题预览 · <strong>{preview}</strong>
|
||||
</p>
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
import { Images, Loader2 } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import Modal from "@/components/Modal";
|
||||
import { apiMyMedia, type MediaAttachment } from "@/lib/api";
|
||||
import { mediaURLFitsSlot, type BrandSlot } from "@/lib/brand";
|
||||
import { apiAdminMediaLibrary, apiMyMedia } from "@/lib/api";
|
||||
import { normalizeBrandURL, type BrandSlot } from "@/lib/brand";
|
||||
import { isOwnImage, variantURL, widthSrcSet } from "@/lib/responsiveImage";
|
||||
|
||||
const SLOT_LABEL: Record<BrandSlot, string> = {
|
||||
logo_light: "浅色 Logo",
|
||||
@@ -12,6 +13,13 @@ const SLOT_LABEL: Record<BrandSlot, string> = {
|
||||
favicon: "Favicon",
|
||||
};
|
||||
|
||||
/** 选图条目:本人附件带 attachmentId;品牌目录历史图仅 URL(已在品牌目录,无需复制) */
|
||||
export type BrandPickItem = {
|
||||
key: string;
|
||||
url: string;
|
||||
attachmentId: number | null;
|
||||
};
|
||||
|
||||
export default function BrandMediaPicker({
|
||||
open,
|
||||
slot,
|
||||
@@ -21,9 +29,9 @@ export default function BrandMediaPicker({
|
||||
open: boolean;
|
||||
slot: BrandSlot;
|
||||
onClose: () => void;
|
||||
onPick: (item: MediaAttachment) => void;
|
||||
onPick: (item: BrandPickItem) => void;
|
||||
}) {
|
||||
const [items, setItems] = useState<MediaAttachment[]>([]);
|
||||
const [items, setItems] = useState<BrandPickItem[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
@@ -32,16 +40,29 @@ export default function BrandMediaPicker({
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
void apiMyMedia()
|
||||
.then((res) => {
|
||||
// 本人附件 + 媒体库盘点里的品牌目录历史图(品牌图不落附件,需合并展示)
|
||||
Promise.all([apiMyMedia(), apiAdminMediaLibrary().catch(() => null)])
|
||||
.then(([mediaRes, libRes]) => {
|
||||
if (cancelled) return;
|
||||
if (res.error) {
|
||||
setError(res.error);
|
||||
if (mediaRes.error) {
|
||||
setError(mediaRes.error);
|
||||
setItems([]);
|
||||
return;
|
||||
}
|
||||
const all = res.attachments || [];
|
||||
setItems(all.filter((item) => mediaURLFitsSlot(slot, item.url)));
|
||||
const out: BrandPickItem[] = (mediaRes.attachments || []).map((a) => ({
|
||||
key: `att-${a.id}`,
|
||||
url: a.url,
|
||||
attachmentId: a.id,
|
||||
}));
|
||||
const seen = new Set(out.map((i) => i.url));
|
||||
for (const it of libRes?.items || []) {
|
||||
if (it.category !== "brand") continue;
|
||||
if (!normalizeBrandURL(slot, it.url)) continue;
|
||||
if (seen.has(it.url)) continue;
|
||||
seen.add(it.url);
|
||||
out.unshift({ key: `brand-${it.url}`, url: it.url, attachmentId: null });
|
||||
}
|
||||
setItems(out);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError("加载媒体库失败");
|
||||
@@ -58,7 +79,7 @@ export default function BrandMediaPicker({
|
||||
<Modal
|
||||
open={open}
|
||||
title={`从媒体库选择 · ${SLOT_LABEL[slot]}`}
|
||||
description="只列出格式符合的图片。保存后会复制一份到品牌目录,之后删除原图不会影响 Logo。"
|
||||
description="位图选中后进入裁剪并转成 WebP;SVG / ICO 与历史品牌图直接引用,之后删除原图不会影响 Logo。"
|
||||
onClose={onClose}
|
||||
maxWidthClass="max-w-lg"
|
||||
dismissOnOverlay
|
||||
@@ -72,12 +93,12 @@ export default function BrandMediaPicker({
|
||||
{error}
|
||||
</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="meta text-[13px] py-6 text-center">没有可用图片。Logo 需要 PNG / WebP / SVG,Favicon 还可选 ICO。</p>
|
||||
<p className="meta text-[13px] py-6 text-center">媒体库还没有图片,先上传一张吧。</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-4 sm:grid-cols-5 gap-2">
|
||||
{items.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
key={item.key}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onPick(item);
|
||||
@@ -88,7 +109,14 @@ export default function BrandMediaPicker({
|
||||
data-tip="用作草稿预览,点保存后才生效"
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={item.url} alt={`${SLOT_LABEL[slot]}候选图`} className="w-full h-full object-contain" loading="lazy" />
|
||||
<img
|
||||
src={isOwnImage(item.url) ? variantURL(item.url, 160) : item.url}
|
||||
srcSet={isOwnImage(item.url) ? widthSrcSet(item.url, [96, 160, 256, 384]) : undefined}
|
||||
sizes="(max-width:520px) 23vw, 96px"
|
||||
alt={`${SLOT_LABEL[slot]}候选图`}
|
||||
className="w-full h-full object-contain"
|
||||
loading="lazy"
|
||||
/>
|
||||
<span
|
||||
className="pointer-events-none absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100"
|
||||
style={{ background: "color-mix(in srgb, var(--ink) 40%, transparent)", color: "#fff" }}
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
"use client";
|
||||
|
||||
import { Check, ImagePlus, Images, Link2, X } from "lucide-react";
|
||||
import { Check, Crop, ImagePlus, Images, Link2, X } from "lucide-react";
|
||||
import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import {
|
||||
AdminSegmented,
|
||||
AdminSettingsActions,
|
||||
AdminSettingsGroup,
|
||||
} from "@/components/admin";
|
||||
import BrandCropModal from "@/components/BrandCropModal";
|
||||
import BrandLockup from "@/components/BrandLockup";
|
||||
import { apiBrandFromMedia, apiUpdateSiteSettings, apiUploadBrand, type PublicSettings } from "@/lib/api";
|
||||
import {
|
||||
BRAND_LOGO_FITS,
|
||||
BRAND_LOGO_SIZES,
|
||||
brandAccept,
|
||||
brandAliasPath,
|
||||
brandFileOk,
|
||||
normalizeBrandURL,
|
||||
type BrandLogoFit,
|
||||
type BrandLogoSize,
|
||||
type BrandMark,
|
||||
type BrandSlot,
|
||||
} from "@/lib/brand";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { densitySrcSet, isOwnImage, pickVariantWidth, variantURL } from "@/lib/responsiveImage";
|
||||
import BrandMediaPicker from "./BrandMediaPicker";
|
||||
|
||||
type SlotDraft = {
|
||||
@@ -76,6 +77,9 @@ export default function BrandSeoPanel({
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState("");
|
||||
const [picker, setPicker] = useState<BrandSlot | null>(null);
|
||||
const [cropSlot, setCropSlot] = useState<BrandSlot | null>(null);
|
||||
const [cropSeedFile, setCropSeedFile] = useState<File | null>(null);
|
||||
const [cropSeedUrl, setCropSeedUrl] = useState("");
|
||||
const [copiedSlot, setCopiedSlot] = useState<BrandSlot | null>(null);
|
||||
const blobs = useRef<string[]>([]);
|
||||
const saveGen = useRef(0);
|
||||
@@ -122,6 +126,18 @@ export default function BrandSeoPanel({
|
||||
return draft.committed;
|
||||
};
|
||||
|
||||
const openCrop = (slot: BrandSlot, file: File | null, url: string) => {
|
||||
setCropSlot(slot);
|
||||
setCropSeedFile(file);
|
||||
setCropSeedUrl(url);
|
||||
};
|
||||
|
||||
const closeCrop = () => {
|
||||
setCropSlot(null);
|
||||
setCropSeedFile(null);
|
||||
setCropSeedUrl("");
|
||||
};
|
||||
|
||||
const discard = () => {
|
||||
[light, dark, favicon].forEach((d) => {
|
||||
if (d.blob) URL.revokeObjectURL(d.blob);
|
||||
@@ -233,8 +249,13 @@ export default function BrandSeoPanel({
|
||||
<div key={slot} className={`admin-brand-asset${compact ? " is-compact" : ""}`}>
|
||||
<div className={`admin-brand-swatch ${swatchClass}`}>
|
||||
{preview ? (
|
||||
// 预览槽(≤56px 高,宽标可能更宽):本站图走 160/384 密度变体
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={preview} alt="" />
|
||||
<img
|
||||
src={isOwnImage(preview) ? variantURL(preview, pickVariantWidth(384)) : preview}
|
||||
srcSet={isOwnImage(preview) ? densitySrcSet(preview, 384) : undefined}
|
||||
alt=""
|
||||
/>
|
||||
) : (
|
||||
<span>未设置</span>
|
||||
)}
|
||||
@@ -271,7 +292,14 @@ export default function BrandSeoPanel({
|
||||
toast(err);
|
||||
return;
|
||||
}
|
||||
replaceFile(slot, file);
|
||||
// SVG / ICO 无需裁剪,直接走原流程
|
||||
const isVector = file.name.toLowerCase().endsWith(".svg");
|
||||
const isIco = file.name.toLowerCase().endsWith(".ico");
|
||||
if (isVector || isIco) {
|
||||
replaceFile(slot, file);
|
||||
return;
|
||||
}
|
||||
openCrop(slot, file, "");
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
@@ -283,6 +311,17 @@ export default function BrandSeoPanel({
|
||||
>
|
||||
<Images size={14} /> 库
|
||||
</button>
|
||||
{preview && !/\.(svg|ico)(\?.*)?$/i.test(preview) ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-line btn-sm"
|
||||
disabled={saving}
|
||||
title="调整画幅、铺法或重新裁剪"
|
||||
onClick={() => openCrop(slot, null, preview)}
|
||||
>
|
||||
<Crop size={14} /> 调整
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="admin-icon-btn"
|
||||
@@ -331,7 +370,7 @@ export default function BrandSeoPanel({
|
||||
frame
|
||||
name={initial.site_name}
|
||||
wordmark={initial.site_wordmark}
|
||||
slogan={initial.site_slogan}
|
||||
slogan={initial.brand_slogan_visible ? initial.site_slogan : ""}
|
||||
logoLight={previewOf(light)}
|
||||
logoDark={previewOf(dark)}
|
||||
/>
|
||||
@@ -358,46 +397,9 @@ export default function BrandSeoPanel({
|
||||
/>
|
||||
</div>
|
||||
{mark !== "text" ? (
|
||||
<>
|
||||
<div className="admin-brand-studio-field">
|
||||
<span className="admin-brand-studio-kicker">比例</span>
|
||||
<div className="admin-brand-size-row" role="group" aria-label="Logo 比例">
|
||||
{BRAND_LOGO_SIZES.map((item) => {
|
||||
const on = logoSize === item.id;
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={`admin-brand-size-chip${on ? " is-on" : ""}`}
|
||||
onClick={() => {
|
||||
setLogoSize(item.id);
|
||||
if (saveError) setSaveError("");
|
||||
}}
|
||||
>
|
||||
<span className="admin-brand-size-chip-label">{item.label}</span>
|
||||
<span className="admin-brand-size-chip-px">
|
||||
{item.w}×{item.h}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="admin-brand-studio-field">
|
||||
<span className="admin-brand-studio-kicker">铺法</span>
|
||||
<AdminSegmented
|
||||
role="group"
|
||||
size="sm"
|
||||
ariaLabel="适配方式"
|
||||
value={logoFit}
|
||||
onChange={(v) => {
|
||||
setLogoFit(v);
|
||||
if (saveError) setSaveError("");
|
||||
}}
|
||||
options={BRAND_LOGO_FITS.map((item) => ({ key: item.id, label: item.label }))}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
<p className="admin-brand-studio-field text-[11.5px] self-center mb-0.5" style={{ color: "var(--ink-3)" }}>
|
||||
画幅与铺法在上传/调整图片的裁剪弹窗中设置
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -412,11 +414,60 @@ export default function BrandSeoPanel({
|
||||
onClose={() => setPicker(null)}
|
||||
onPick={(item) => {
|
||||
if (!picker) return;
|
||||
const [prev, set] = drafts[picker];
|
||||
if (prev.blob) URL.revokeObjectURL(prev.blob);
|
||||
set({ ...prev, file: null, blob: "", mediaId: item.id, mediaUrl: item.url });
|
||||
const slot = picker;
|
||||
setPicker(null);
|
||||
// 已是品牌目录的历史图(含裁剪产物):直接引用,不再复制
|
||||
const brandURL = normalizeBrandURL(slot, item.url);
|
||||
if (brandURL) {
|
||||
const [prev, set] = drafts[slot];
|
||||
if (prev.blob) URL.revokeObjectURL(prev.blob);
|
||||
set({ committed: brandURL, file: null, blob: "", mediaId: null, mediaUrl: "" });
|
||||
return;
|
||||
}
|
||||
const lower = item.url.toLowerCase();
|
||||
const isVector = lower.endsWith(".svg");
|
||||
const isIco = lower.endsWith(".ico");
|
||||
// SVG / ICO 不可裁剪,复制一份进品牌目录后引用
|
||||
if ((isVector || isIco) && item.attachmentId != null) {
|
||||
const [prev, set] = drafts[slot];
|
||||
if (prev.blob) URL.revokeObjectURL(prev.blob);
|
||||
set({ ...prev, file: null, blob: "", mediaId: item.attachmentId, mediaUrl: item.url });
|
||||
return;
|
||||
}
|
||||
openCrop(slot, null, item.url);
|
||||
}}
|
||||
/>
|
||||
{cropSlot ? (
|
||||
<BrandCropModal
|
||||
open
|
||||
slot={cropSlot}
|
||||
seedFile={cropSeedFile}
|
||||
seedUrl={cropSeedUrl}
|
||||
logoSize={logoSize}
|
||||
logoFit={logoFit}
|
||||
onSizeChange={(s) => {
|
||||
setLogoSize(s);
|
||||
if (saveError) setSaveError("");
|
||||
}}
|
||||
onFitChange={(f) => {
|
||||
setLogoFit(f);
|
||||
if (saveError) setSaveError("");
|
||||
}}
|
||||
onClose={closeCrop}
|
||||
onSeedConsumed={() => {
|
||||
setCropSeedFile(null);
|
||||
setCropSeedUrl("");
|
||||
}}
|
||||
onCropped={(url) => {
|
||||
const [, set] = drafts[cropSlot];
|
||||
set((prev) => {
|
||||
if (prev.blob) URL.revokeObjectURL(prev.blob);
|
||||
return { committed: url, file: null, blob: "", mediaId: null, mediaUrl: "" };
|
||||
});
|
||||
closeCrop();
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</AdminSettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||