feat: 书库导入导出/图片变体/书籍搜索/小组件运行时等

新增:
- 书库导入导出(library_import/library_export)及测试
- 图片变体生成(image_variants)与响应式图片(responsiveImage)
- 书籍搜索(bookSearch)+ BookSearch/LibrarySearchGrid 组件
- 小组件运行时(widgetRuntime)与静态检查(widgetLint)
- 上传缓存中间件(upload_cache)与字体 CSS 提取脚本

其它:
- 后端 handlers/services 全量调整
- 前端页面、组件、库函数与配置更新
This commit is contained in:
2026-10-01 03:06:05 +08:00
parent 7fbd6ba699
commit ff2ab286fb
141 changed files with 7527 additions and 1407 deletions

View File

@@ -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)

View File

@@ -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)

View File

@@ -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

View File

@@ -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,
})
}

View File

@@ -4,6 +4,7 @@ import (
"errors"
"net/http"
"strconv"
"time"
"github.com/freefire/jiang13-bbs/middleware"
"github.com/freefire/jiang13-bbs/model"
@@ -42,6 +43,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 {
@@ -322,7 +343,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 +356,59 @@ 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,前端按系统消息渲染)
if sysMsg != nil && sysMsg.ID > 0 {
h.Hub.BroadcastRoom(realtime.RoomChat(roomID), realtime.Envelope{
Type: realtime.EventChatMessage,
Data: gin.H{
"message": 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 站长任命/撤销群管理员

View File

@@ -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"`

View File

@@ -10,36 +10,36 @@ 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
}

View File

@@ -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 空=章,非空=节)

View File

@@ -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,

View File

@@ -313,7 +313,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)
}

View File

@@ -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,
})
}

View File

@@ -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"

View File

@@ -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),