refactor: 文件行数超标拆解(Service + Controller 9/16 完成)
- Service 层:energy_service → energize/operations/admin/query 四文件 - Service 层:post_service → helpers/audit + 核心 CRUD 保留 - Service 层:favorite_service → items + 核心文件夹操作保留 - Service 层:auth_service → password + 核心注册/登录保留 - Service 层:notification_service → notify + 核心列表/已读保留 - Service 层:audit_service → review + 核心列表/详情保留 - Controller 层:studio_controller → page/write/api/post_api/action 五文件 - Controller 层:post_controller → page/api/upload 三文件 - Controller 层:comment_controller → list/write/action/upload 四文件 - 清理未使用导入(notification_service.go 移除 fmt)
This commit is contained in:
63
internal/controller/comment_action_controller.go
Normal file
63
internal/controller/comment_action_controller.go
Normal file
@ -0,0 +1,63 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Delete DELETE /api/comments/:id
|
||||
func (ctrl *CommentController) Delete(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
commentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
// 权限检查由 service 层统一处理
|
||||
isAdmin := model.HasMinRole(role, model.RoleAdmin)
|
||||
if err := ctrl.commentService.Delete(uint(commentID), uid, isAdmin); err != nil {
|
||||
if errors.Is(err, common.ErrPermissionDenied) {
|
||||
common.Error(c, http.StatusForbidden, err.Error())
|
||||
return
|
||||
}
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "删除成功")
|
||||
}
|
||||
|
||||
// SearchUsers GET /api/users/search?q=keyword
|
||||
func (ctrl *CommentController) SearchUsers(c *gin.Context) {
|
||||
_, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
q := c.Query("q")
|
||||
if q == "" {
|
||||
common.Ok(c, []model.UserSearchResult{})
|
||||
return
|
||||
}
|
||||
|
||||
users, err := ctrl.commentService.SearchUsers(q)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "搜索用户失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, users)
|
||||
}
|
||||
@ -1,25 +1,5 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CommentController 评论控制器
|
||||
type CommentController struct {
|
||||
commentService commentUseCase
|
||||
@ -29,258 +9,3 @@ type CommentController struct {
|
||||
func NewCommentController(cs commentUseCase) *CommentController {
|
||||
return &CommentController{commentService: cs}
|
||||
}
|
||||
|
||||
// ListRootComments 获取文章顶级评论 GET /api/posts/:id/comments
|
||||
func (ctrl *CommentController) ListRootComments(c *gin.Context) {
|
||||
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
comments, total, err := ctrl.commentService.ListRootComments(uint(postID), page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取评论失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{
|
||||
"items": comments,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"total_pages": common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
|
||||
// ListReplies 获取顶级评论的全部回复 GET /api/posts/:id/comments/:root_id/replies
|
||||
func (ctrl *CommentController) ListReplies(c *gin.Context) {
|
||||
rootID, err := strconv.ParseUint(c.Param("root_id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
replies, err := ctrl.commentService.ListReplies(uint(rootID))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取回复失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{"replies": replies})
|
||||
}
|
||||
|
||||
// CreateRoot POST /api/posts/:id/comments
|
||||
func (ctrl *CommentController) CreateRoot(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Body string `json:"body" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请输入评论内容")
|
||||
return
|
||||
}
|
||||
|
||||
comment, err := ctrl.commentService.CreateRoot(uid, uint(postID), req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, comment)
|
||||
}
|
||||
|
||||
// CreateReply POST /api/comments/:id/reply
|
||||
func (ctrl *CommentController) CreateReply(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
parentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Body string `json:"body" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请输入回复内容")
|
||||
return
|
||||
}
|
||||
|
||||
reply, err := ctrl.commentService.CreateReply(uid, uint(parentID), req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, reply)
|
||||
}
|
||||
|
||||
// Delete DELETE /api/comments/:id
|
||||
func (ctrl *CommentController) Delete(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
commentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
// 权限检查由 service 层统一处理
|
||||
isAdmin := model.HasMinRole(role, model.RoleAdmin)
|
||||
if err := ctrl.commentService.Delete(uint(commentID), uid, isAdmin); err != nil {
|
||||
if errors.Is(err, common.ErrPermissionDenied) {
|
||||
common.Error(c, http.StatusForbidden, err.Error())
|
||||
return
|
||||
}
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "删除成功")
|
||||
}
|
||||
|
||||
// SearchUsers GET /api/users/search?q=keyword
|
||||
func (ctrl *CommentController) SearchUsers(c *gin.Context) {
|
||||
_, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
q := c.Query("q")
|
||||
if q == "" {
|
||||
common.Ok(c, []model.UserSearchResult{})
|
||||
return
|
||||
}
|
||||
|
||||
users, err := ctrl.commentService.SearchUsers(q)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "搜索用户失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, users)
|
||||
}
|
||||
|
||||
// UploadImage 上传评论图片 POST /api/comments/upload-image
|
||||
// 需要 LV4+(Exp ≥ 1500),复用帖子图片上传的 WebP 转码逻辑
|
||||
func (ctrl *CommentController) UploadImage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
// LV4+ 检查(Exp ≥ 1500)
|
||||
expVal, exists := c.Get("exp")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusForbidden, "无法获取经验值")
|
||||
return
|
||||
}
|
||||
exp := expVal.(int)
|
||||
if exp < 1500 {
|
||||
common.Error(c, http.StatusForbidden, "需 Lv4 以上才能上传评论图片")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请选择文件")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查扩展名
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
allowedExt := map[string]bool{".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true}
|
||||
if !allowedExt[ext] {
|
||||
common.Error(c, http.StatusBadRequest, "仅支持 jpg/jpeg/png/gif/webp 格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 限制 5MB
|
||||
if header.Size > 5<<20 {
|
||||
common.Error(c, http.StatusBadRequest, "图片大小不能超过 5MB")
|
||||
return
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "读取文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
storageDir := "storage/uploads/posts"
|
||||
if err := os.MkdirAll(storageDir, 0755); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "存储初始化失败")
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().UnixMilli()
|
||||
isJPEGPNG := ext == ".jpg" || ext == ".jpeg" || ext == ".png"
|
||||
|
||||
var savePath, url string
|
||||
|
||||
// JPEG/PNG 转 WebP
|
||||
if isJPEGPNG {
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效")
|
||||
return
|
||||
}
|
||||
webpData := encodeWebPBinary(img, len(data))
|
||||
if webpData != nil && len(webpData) < len(data) {
|
||||
filename := strconv.FormatUint(uint64(uid), 10) + "_" + strconv.FormatInt(ts, 10) + ".webp"
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
os.WriteFile(savePath, webpData, 0644)
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
}
|
||||
|
||||
// 回退存储
|
||||
if savePath == "" {
|
||||
dataOut := data
|
||||
if isJPEGPNG {
|
||||
decImg, _, decErr := image.Decode(bytes.NewReader(data))
|
||||
if decErr == nil {
|
||||
var buf bytes.Buffer
|
||||
if ext == ".png" {
|
||||
png.Encode(&buf, decImg)
|
||||
} else {
|
||||
jpeg.Encode(&buf, decImg, &jpeg.Options{Quality: 92})
|
||||
}
|
||||
dataOut = buf.Bytes()
|
||||
}
|
||||
}
|
||||
filename := strconv.FormatUint(uint64(uid), 10) + "_" + strconv.FormatInt(ts, 10) + ext
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
os.WriteFile(savePath, dataOut, 0644)
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
|
||||
// 返回标准 JSON(前端将 URL 插入评论文本)
|
||||
common.Ok(c, gin.H{"url": url})
|
||||
}
|
||||
|
||||
52
internal/controller/comment_list_controller.go
Normal file
52
internal/controller/comment_list_controller.go
Normal file
@ -0,0 +1,52 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ListRootComments 获取文章顶级评论 GET /api/posts/:id/comments
|
||||
func (ctrl *CommentController) ListRootComments(c *gin.Context) {
|
||||
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
comments, total, err := ctrl.commentService.ListRootComments(uint(postID), page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取评论失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{
|
||||
"items": comments,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"total_pages": common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
|
||||
// ListReplies 获取顶级评论的全部回复 GET /api/posts/:id/comments/:root_id/replies
|
||||
func (ctrl *CommentController) ListReplies(c *gin.Context) {
|
||||
rootID, err := strconv.ParseUint(c.Param("root_id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
replies, err := ctrl.commentService.ListReplies(uint(rootID))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取回复失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{"replies": replies})
|
||||
}
|
||||
119
internal/controller/comment_upload_controller.go
Normal file
119
internal/controller/comment_upload_controller.go
Normal file
@ -0,0 +1,119 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UploadImage 上传评论图片 POST /api/comments/upload-image
|
||||
// 需要 LV4+(Exp ≥ 1500),复用帖子图片上传的 WebP 转码逻辑
|
||||
func (ctrl *CommentController) UploadImage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
// LV4+ 检查(Exp ≥ 1500)
|
||||
expVal, exists := c.Get("exp")
|
||||
if !exists {
|
||||
common.Error(c, http.StatusForbidden, "无法获取经验值")
|
||||
return
|
||||
}
|
||||
exp := expVal.(int)
|
||||
if exp < 1500 {
|
||||
common.Error(c, http.StatusForbidden, "需 Lv4 以上才能上传评论图片")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请选择文件")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查扩展名
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
allowedExt := map[string]bool{".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true}
|
||||
if !allowedExt[ext] {
|
||||
common.Error(c, http.StatusBadRequest, "仅支持 jpg/jpeg/png/gif/webp 格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 限制 5MB
|
||||
if header.Size > 5<<20 {
|
||||
common.Error(c, http.StatusBadRequest, "图片大小不能超过 5MB")
|
||||
return
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "读取文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
storageDir := "storage/uploads/posts"
|
||||
if err := os.MkdirAll(storageDir, 0755); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "存储初始化失败")
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().UnixMilli()
|
||||
isJPEGPNG := ext == ".jpg" || ext == ".jpeg" || ext == ".png"
|
||||
|
||||
var savePath, url string
|
||||
|
||||
// JPEG/PNG 转 WebP
|
||||
if isJPEGPNG {
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效")
|
||||
return
|
||||
}
|
||||
webpData := encodeWebPBinary(img, len(data))
|
||||
if webpData != nil && len(webpData) < len(data) {
|
||||
filename := strconv.FormatUint(uint64(uid), 10) + "_" + strconv.FormatInt(ts, 10) + ".webp"
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
os.WriteFile(savePath, webpData, 0644)
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
}
|
||||
|
||||
// 回退存储
|
||||
if savePath == "" {
|
||||
dataOut := data
|
||||
if isJPEGPNG {
|
||||
decImg, _, decErr := image.Decode(bytes.NewReader(data))
|
||||
if decErr == nil {
|
||||
var buf bytes.Buffer
|
||||
if ext == ".png" {
|
||||
png.Encode(&buf, decImg)
|
||||
} else {
|
||||
jpeg.Encode(&buf, decImg, &jpeg.Options{Quality: 92})
|
||||
}
|
||||
dataOut = buf.Bytes()
|
||||
}
|
||||
}
|
||||
filename := strconv.FormatUint(uint64(uid), 10) + "_" + strconv.FormatInt(ts, 10) + ext
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
os.WriteFile(savePath, dataOut, 0644)
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
|
||||
// 返回标准 JSON(前端将 URL 插入评论文本)
|
||||
common.Ok(c, gin.H{"url": url})
|
||||
}
|
||||
72
internal/controller/comment_write_controller.go
Normal file
72
internal/controller/comment_write_controller.go
Normal file
@ -0,0 +1,72 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CreateRoot POST /api/posts/:id/comments
|
||||
func (ctrl *CommentController) CreateRoot(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
postID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的文章ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Body string `json:"body" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请输入评论内容")
|
||||
return
|
||||
}
|
||||
|
||||
comment, err := ctrl.commentService.CreateRoot(uid, uint(postID), req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, comment)
|
||||
}
|
||||
|
||||
// CreateReply POST /api/comments/:id/reply
|
||||
func (ctrl *CommentController) CreateReply(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
parentID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的评论ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Body string `json:"body" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请输入回复内容")
|
||||
return
|
||||
}
|
||||
|
||||
reply, err := ctrl.commentService.CreateReply(uid, uint(parentID), req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, reply)
|
||||
}
|
||||
109
internal/controller/post_api_controller.go
Normal file
109
internal/controller/post_api_controller.go
Normal file
@ -0,0 +1,109 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Submit API 提交审核
|
||||
func (ctrl *PostController) Submit(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if post.UserID != uid {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
|
||||
if errors.Is(err, common.ErrPostCannotSubmit) || errors.Is(err, common.ErrPostNotFound) {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
common.Error(c, http.StatusInternalServerError, "提交审核失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已提交审核")
|
||||
}
|
||||
|
||||
// ListAPI 帖子列表 JSON API
|
||||
func (ctrl *PostController) ListAPI(c *gin.Context) {
|
||||
keyword := c.Query("keyword")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.List(keyword, page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取帖子列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, model.PostListResult{
|
||||
Items: posts,
|
||||
Total: total,
|
||||
Page: page,
|
||||
TotalPages: common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
|
||||
// ShowAPI 帖子详情 JSON API
|
||||
func (ctrl *PostController) ShowAPI(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
|
||||
uid, role, _ := common.GetGinUser(c)
|
||||
|
||||
// 权限控制:非 approved 帖子仅作者和 moderator+ 可见
|
||||
if post.Status != model.PostStatusApproved {
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 已登录用户阅读计数(已发布帖子,自动去重+防刷)
|
||||
if uid > 0 && post.Status == model.PostStatusApproved {
|
||||
ctrl.postService.RecordRead(uid, post.ID)
|
||||
}
|
||||
|
||||
// 访客阅读计数(基于 Cookie 标识去重+防刷)
|
||||
if uid == 0 && post.Status == model.PostStatusApproved {
|
||||
vid := ctrl.getVisitorID(c)
|
||||
ctrl.postService.RecordGuestRead(vid, post.ID)
|
||||
}
|
||||
|
||||
ctrl.applyShortcode(post)
|
||||
|
||||
common.Ok(c, post)
|
||||
}
|
||||
@ -4,21 +4,8 @@ import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
_ "image/gif" // 仅注册 GIF 解码器,不重编码(会丢失动画)
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
"metazone.cc/metalab/internal/service"
|
||||
|
||||
@ -37,337 +24,11 @@ func NewPostController(ps postUseCase, scs *service.ShortcodeService) *PostContr
|
||||
return &PostController{postService: ps, shortcodeSvc: scs}
|
||||
}
|
||||
|
||||
// ListPage 帖子列表页
|
||||
func (ctrl *PostController) ListPage(c *gin.Context) {
|
||||
keyword := c.Query("keyword")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.List(keyword, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "posts/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "社区帖子",
|
||||
"Error": "加载帖子列表失败",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
totalPages := common.PageCount(total, pageSize)
|
||||
prevPage := page - 1
|
||||
if prevPage < 1 {
|
||||
prevPage = 1
|
||||
}
|
||||
nextPage := page + 1
|
||||
if nextPage > totalPages {
|
||||
nextPage = totalPages
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "posts/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "社区帖子",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"TotalPages": totalPages,
|
||||
"PrevPage": prevPage,
|
||||
"NextPage": nextPage,
|
||||
"Keyword": keyword,
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// ShowPage 帖子详情页
|
||||
func (ctrl *PostController) ShowPage(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
uid, role, _ := common.GetGinUser(c)
|
||||
|
||||
// 仅 approved 公开可见(作者本人 + moderator+ 可预览其他状态)
|
||||
if post.Status != model.PostStatusApproved && !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
// 未登录用户:引导登录后回到当前帖子
|
||||
if uid == 0 {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
// 已登录用户阅读计数(已发布帖子,自动去重+防刷)
|
||||
if uid > 0 && post.Status == model.PostStatusApproved {
|
||||
ctrl.postService.RecordRead(uid, post.ID)
|
||||
}
|
||||
|
||||
// 访客阅读计数(基于 Cookie 标识去重+防刷)
|
||||
if uid == 0 && post.Status == model.PostStatusApproved {
|
||||
vid := ctrl.getVisitorID(c)
|
||||
ctrl.postService.RecordGuestRead(vid, post.ID)
|
||||
}
|
||||
|
||||
ctrl.applyShortcode(post)
|
||||
|
||||
// Open Graph 社交分享数据
|
||||
ogImage := common.ExtractFirstImage(post.Body)
|
||||
if ogImage != "" && !strings.HasPrefix(ogImage, "http") {
|
||||
prefix := ""
|
||||
if !strings.HasPrefix(ogImage, "/") {
|
||||
prefix = "/"
|
||||
}
|
||||
ogImage = "https://" + c.Request.Host + prefix + ogImage
|
||||
}
|
||||
ogURL := fmt.Sprintf("https://%s/posts/%d", c.Request.Host, id)
|
||||
|
||||
c.HTML(http.StatusOK, "posts/show.html", common.BuildPageData(c, gin.H{
|
||||
"Title": post.Title,
|
||||
"Post": post,
|
||||
"UID": uid,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
"OgTitle": post.Title,
|
||||
"OgDescription": post.Excerpt,
|
||||
"OgImage": ogImage,
|
||||
"OgURL": ogURL,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
// Submit API 提交审核
|
||||
func (ctrl *PostController) Submit(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
|
||||
if post.UserID != uid {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
|
||||
if errors.Is(err, common.ErrPostCannotSubmit) || errors.Is(err, common.ErrPostNotFound) {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
} else {
|
||||
common.Error(c, http.StatusInternalServerError, "提交审核失败")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已提交审核")
|
||||
}
|
||||
|
||||
// ListAPI 帖子列表 JSON API
|
||||
func (ctrl *PostController) ListAPI(c *gin.Context) {
|
||||
keyword := c.Query("keyword")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.List(keyword, page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取帖子列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, model.PostListResult{
|
||||
Items: posts,
|
||||
Total: total,
|
||||
Page: page,
|
||||
TotalPages: common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
|
||||
// ShowAPI 帖子详情 JSON API
|
||||
func (ctrl *PostController) ShowAPI(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
|
||||
uid, role, _ := common.GetGinUser(c)
|
||||
|
||||
// 权限控制:非 approved 帖子仅作者和 moderator+ 可见
|
||||
if post.Status != model.PostStatusApproved {
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 已登录用户阅读计数(已发布帖子,自动去重+防刷)
|
||||
if uid > 0 && post.Status == model.PostStatusApproved {
|
||||
ctrl.postService.RecordRead(uid, post.ID)
|
||||
}
|
||||
|
||||
// 访客阅读计数(基于 Cookie 标识去重+防刷)
|
||||
if uid == 0 && post.Status == model.PostStatusApproved {
|
||||
vid := ctrl.getVisitorID(c)
|
||||
ctrl.postService.RecordGuestRead(vid, post.ID)
|
||||
}
|
||||
|
||||
ctrl.applyShortcode(post)
|
||||
|
||||
common.Ok(c, post)
|
||||
}
|
||||
|
||||
// allowedImageExt 允许的图片扩展名
|
||||
var allowedImageExt = map[string]bool{
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
||||
}
|
||||
|
||||
// UploadImage 上传帖子图片(需登录,multipart/form-data)
|
||||
// JPEG/PNG 自动转 WebP quality 80 存储,保留原尺寸不 resize
|
||||
func (ctrl *PostController) UploadImage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请选择文件")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查扩展名
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
if !allowedImageExt[ext] {
|
||||
common.Error(c, http.StatusBadRequest, "仅支持 jpg / jpeg / png / gif / webp 格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 限制 5MB
|
||||
maxSize := int64(5 << 20)
|
||||
if header.Size > maxSize {
|
||||
common.Error(c, http.StatusBadRequest, "图片大小不能超过 5MB")
|
||||
return
|
||||
}
|
||||
|
||||
// 读取全部数据(后续 WebP 转换需要)
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "读取文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 存储路径
|
||||
storageDir := "storage/uploads/posts"
|
||||
if err := os.MkdirAll(storageDir, 0755); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "存储初始化失败")
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().UnixMilli()
|
||||
var savePath, url string
|
||||
|
||||
isJPEGPNG := ext == ".jpg" || ext == ".jpeg" || ext == ".png"
|
||||
isWebP := ext == ".webp"
|
||||
isGIF := ext == ".gif"
|
||||
|
||||
// 强制解码验证文件是否为有效图片(防伪扩展名、图片投毒),验证失败直接拒绝
|
||||
// JPEG/PNG:解码后做 WebP 压缩(二分查找质量,目标 ≤ 原文件大小)
|
||||
if isJPEGPNG {
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
webpData := encodeWebPBinary(img, len(data))
|
||||
if webpData != nil && len(webpData) < len(data) {
|
||||
filename := fmt.Sprintf("%d_%d.webp", uid, ts)
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
if err := os.WriteFile(savePath, webpData, 0644); err == nil {
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GIF:仅解码验证,不转换
|
||||
if isGIF {
|
||||
if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// WebP:仅解码验证,不重复编码
|
||||
if isWebP {
|
||||
if _, err := webp.Decode(bytes.NewReader(data)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 回退存储:JPEG/PNG 重编码剥离元数据;WebP 已验证直接存;GIF 不重编(丢动画)
|
||||
if savePath == "" {
|
||||
dataOut := data
|
||||
|
||||
if isJPEGPNG {
|
||||
decImg, _, decErr := image.Decode(bytes.NewReader(data))
|
||||
if decErr == nil {
|
||||
var buf bytes.Buffer
|
||||
var encErr error
|
||||
if ext == ".png" {
|
||||
encErr = png.Encode(&buf, decImg)
|
||||
} else {
|
||||
encErr = jpeg.Encode(&buf, decImg, &jpeg.Options{Quality: 92})
|
||||
}
|
||||
if encErr == nil && buf.Len() > 0 {
|
||||
dataOut = buf.Bytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%d_%d%s", uid, ts, ext)
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
if err := os.WriteFile(savePath, dataOut, 0644); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "保存图片失败")
|
||||
return
|
||||
}
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
|
||||
common.VditorUploadOk(c, map[string]string{header.Filename: url})
|
||||
}
|
||||
|
||||
// visitorCookieName Cookie 名称
|
||||
const visitorCookieName = "visitor_id"
|
||||
|
||||
@ -426,4 +87,3 @@ func encodeWebPBinary(img image.Image, targetBytes int) []byte {
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
|
||||
124
internal/controller/post_page_controller.go
Normal file
124
internal/controller/post_page_controller.go
Normal file
@ -0,0 +1,124 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ListPage 帖子列表页
|
||||
func (ctrl *PostController) ListPage(c *gin.Context) {
|
||||
keyword := c.Query("keyword")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.List(keyword, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "posts/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "社区帖子",
|
||||
"Error": "加载帖子列表失败",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
totalPages := common.PageCount(total, pageSize)
|
||||
prevPage := page - 1
|
||||
if prevPage < 1 {
|
||||
prevPage = 1
|
||||
}
|
||||
nextPage := page + 1
|
||||
if nextPage > totalPages {
|
||||
nextPage = totalPages
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "posts/index.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "社区帖子",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"TotalPages": totalPages,
|
||||
"PrevPage": prevPage,
|
||||
"NextPage": nextPage,
|
||||
"Keyword": keyword,
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// ShowPage 帖子详情页
|
||||
func (ctrl *PostController) ShowPage(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err != nil {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
uid, role, _ := common.GetGinUser(c)
|
||||
|
||||
// 仅 approved 公开可见(作者本人 + moderator+ 可预览其他状态)
|
||||
if post.Status != model.PostStatusApproved && !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
// 未登录用户:引导登录后回到当前帖子
|
||||
if uid == 0 {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
// 已登录用户阅读计数(已发布帖子,自动去重+防刷)
|
||||
if uid > 0 && post.Status == model.PostStatusApproved {
|
||||
ctrl.postService.RecordRead(uid, post.ID)
|
||||
}
|
||||
|
||||
// 访客阅读计数(基于 Cookie 标识去重+防刷)
|
||||
if uid == 0 && post.Status == model.PostStatusApproved {
|
||||
vid := ctrl.getVisitorID(c)
|
||||
ctrl.postService.RecordGuestRead(vid, post.ID)
|
||||
}
|
||||
|
||||
ctrl.applyShortcode(post)
|
||||
|
||||
// Open Graph 社交分享数据
|
||||
ogImage := common.ExtractFirstImage(post.Body)
|
||||
if ogImage != "" && !strings.HasPrefix(ogImage, "http") {
|
||||
prefix := ""
|
||||
if !strings.HasPrefix(ogImage, "/") {
|
||||
prefix = "/"
|
||||
}
|
||||
ogImage = "https://" + c.Request.Host + prefix + ogImage
|
||||
}
|
||||
ogURL := fmt.Sprintf("https://%s/posts/%d", c.Request.Host, id)
|
||||
|
||||
c.HTML(http.StatusOK, "posts/show.html", common.BuildPageData(c, gin.H{
|
||||
"Title": post.Title,
|
||||
"Post": post,
|
||||
"UID": uid,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ExtraCSS": "/static/css/posts.css",
|
||||
"OgTitle": post.Title,
|
||||
"OgDescription": post.Excerpt,
|
||||
"OgImage": ogImage,
|
||||
"OgURL": ogURL,
|
||||
}))
|
||||
}
|
||||
138
internal/controller/post_upload_controller.go
Normal file
138
internal/controller/post_upload_controller.go
Normal file
@ -0,0 +1,138 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif" // 仅注册 GIF 解码器,不重编码(会丢失动画)
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/chai2010/webp"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// UploadImage 上传帖子图片(需登录,multipart/form-data)
|
||||
// JPEG/PNG 自动转 WebP quality 80 存储,保留原尺寸不 resize
|
||||
func (ctrl *PostController) UploadImage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "请选择文件")
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 检查扩展名
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
if !allowedImageExt[ext] {
|
||||
common.Error(c, http.StatusBadRequest, "仅支持 jpg / jpeg / png / gif / webp 格式")
|
||||
return
|
||||
}
|
||||
|
||||
// 限制 5MB
|
||||
maxSize := int64(5 << 20)
|
||||
if header.Size > maxSize {
|
||||
common.Error(c, http.StatusBadRequest, "图片大小不能超过 5MB")
|
||||
return
|
||||
}
|
||||
|
||||
// 读取全部数据(后续 WebP 转换需要)
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "读取文件失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 存储路径
|
||||
storageDir := "storage/uploads/posts"
|
||||
if err := os.MkdirAll(storageDir, 0755); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "存储初始化失败")
|
||||
return
|
||||
}
|
||||
|
||||
ts := time.Now().UnixMilli()
|
||||
var savePath, url string
|
||||
|
||||
isJPEGPNG := ext == ".jpg" || ext == ".jpeg" || ext == ".png"
|
||||
isWebP := ext == ".webp"
|
||||
isGIF := ext == ".gif"
|
||||
|
||||
// 强制解码验证文件是否为有效图片(防伪扩展名、图片投毒),验证失败直接拒绝
|
||||
// JPEG/PNG:解码后做 WebP 压缩(二分查找质量,目标 ≤ 原文件大小)
|
||||
if isJPEGPNG {
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
webpData := encodeWebPBinary(img, len(data))
|
||||
if webpData != nil && len(webpData) < len(data) {
|
||||
filename := fmt.Sprintf("%d_%d.webp", uid, ts)
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
if err := os.WriteFile(savePath, webpData, 0644); err == nil {
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GIF:仅解码验证,不转换
|
||||
if isGIF {
|
||||
if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// WebP:仅解码验证,不重复编码
|
||||
if isWebP {
|
||||
if _, err := webp.Decode(bytes.NewReader(data)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "图片格式无效,请上传有效的图片文件")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 回退存储:JPEG/PNG 重编码剥离元数据;WebP 已验证直接存;GIF 不重编(丢动画)
|
||||
if savePath == "" {
|
||||
dataOut := data
|
||||
|
||||
if isJPEGPNG {
|
||||
decImg, _, decErr := image.Decode(bytes.NewReader(data))
|
||||
if decErr == nil {
|
||||
var buf bytes.Buffer
|
||||
var encErr error
|
||||
if ext == ".png" {
|
||||
encErr = png.Encode(&buf, decImg)
|
||||
} else {
|
||||
encErr = jpeg.Encode(&buf, decImg, &jpeg.Options{Quality: 92})
|
||||
}
|
||||
if encErr == nil && buf.Len() > 0 {
|
||||
dataOut = buf.Bytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filename := fmt.Sprintf("%d_%d%s", uid, ts, ext)
|
||||
savePath = filepath.Join(storageDir, filename)
|
||||
if err := os.WriteFile(savePath, dataOut, 0644); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "保存图片失败")
|
||||
return
|
||||
}
|
||||
url = "/uploads/posts/" + filename
|
||||
}
|
||||
|
||||
common.VditorUploadOk(c, map[string]string{header.Filename: url})
|
||||
}
|
||||
133
internal/controller/studio_action_controller.go
Normal file
133
internal/controller/studio_action_controller.go
Normal file
@ -0,0 +1,133 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Delete 删除帖子
|
||||
func (ctrl *StudioController) Delete(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
authorID := post.UserID
|
||||
|
||||
if err := ctrl.postService.Delete(uint(id)); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 删稿扣作者域能(无视负数,有限重试后静默忽略)
|
||||
if ctrl.energySvc != nil {
|
||||
const maxRetries = 3
|
||||
backoff := 100 * time.Millisecond
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
if err := ctrl.energySvc.DeductOnDeletePost(authorID, uint(id)); err == nil {
|
||||
break
|
||||
}
|
||||
if i < maxRetries-1 {
|
||||
time.Sleep(backoff)
|
||||
backoff *= 2
|
||||
} else {
|
||||
log.Printf("删稿扣域能失败(user=%d, post=%d): %v", authorID, id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
common.OkMessage(c, "删除成功")
|
||||
}
|
||||
|
||||
// Submit 提交审核
|
||||
func (ctrl *StudioController) Submit(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已提交审核")
|
||||
}
|
||||
|
||||
// TrendsAPI 创作中心趋势数据 API GET /api/studio/trends?period=7d|30d|90d
|
||||
func (ctrl *StudioController) TrendsAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
if ctrl.trendsSvc == nil {
|
||||
common.Error(c, http.StatusInternalServerError, "趋势服务不可用")
|
||||
return
|
||||
}
|
||||
|
||||
period := c.DefaultQuery("period", "7d")
|
||||
var days int
|
||||
switch period {
|
||||
case "7d":
|
||||
days = 7
|
||||
case "30d":
|
||||
days = 30
|
||||
case "90d":
|
||||
days = 90
|
||||
default:
|
||||
common.Error(c, http.StatusBadRequest, "无效的时间范围,支持 7d/30d/90d")
|
||||
return
|
||||
}
|
||||
|
||||
since := time.Now().AddDate(0, 0, -days).Format("2006-01-02")
|
||||
|
||||
result, err := ctrl.trendsSvc.GetTrends(uid, since)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取趋势数据失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, result)
|
||||
}
|
||||
54
internal/controller/studio_api_controller.go
Normal file
54
internal/controller/studio_api_controller.go
Normal file
@ -0,0 +1,54 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// OverviewAPI 创作中心数据概览
|
||||
func (ctrl *StudioController) OverviewAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取数据失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, overview)
|
||||
}
|
||||
|
||||
// ListPostsAPI 我的帖子列表(支持状态筛选)
|
||||
func (ctrl *StudioController) ListPostsAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, status, page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{
|
||||
"items": posts,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_pages": common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
@ -1,16 +1,7 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
"metazone.cc/metalab/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// trendsUseCase StudioController 对趋势服务的最小依赖(ISP)
|
||||
@ -20,9 +11,9 @@ type trendsUseCase interface {
|
||||
|
||||
// StudioController 创作中心控制器(SSR 页面 + API)
|
||||
type StudioController struct {
|
||||
postService studioUseCase
|
||||
energySvc energyDeducter
|
||||
trendsSvc trendsUseCase
|
||||
postService studioUseCase
|
||||
energySvc energyDeducter
|
||||
trendsSvc trendsUseCase
|
||||
}
|
||||
|
||||
// NewStudioController 构造函数
|
||||
@ -41,415 +32,3 @@ func (ctrl *StudioController) WithTrendsService(svc trendsUseCase) *StudioContro
|
||||
ctrl.trendsSvc = svc
|
||||
return ctrl
|
||||
}
|
||||
|
||||
// ==============================
|
||||
// SSR 页面方法
|
||||
// ==============================
|
||||
|
||||
// OverviewPage 创作中心首页(数据概览)
|
||||
func (ctrl *StudioController) OverviewPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/overview.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "创作中心",
|
||||
"Error": "加载数据失败",
|
||||
"ActiveTab": "overview",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/overview.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "创作中心",
|
||||
"Overview": overview,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "overview",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// PostsPage 内容管理页
|
||||
func (ctrl *StudioController) PostsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, status, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/posts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "内容管理 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "posts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
overview, _ := ctrl.postService.GetOverview(uid)
|
||||
|
||||
c.HTML(http.StatusOK, "studio/posts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "内容管理 - 创作中心",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"PageSize": pageSize,
|
||||
"TotalPages": common.PageCount(total, pageSize),
|
||||
"CurrentStatus": status,
|
||||
"Overview": overview,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "posts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// DraftsPage 草稿箱页面
|
||||
func (ctrl *StudioController) DraftsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, model.PostStatusDraft, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/drafts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "草稿箱 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "drafts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/drafts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "草稿箱 - 创作中心",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"PageSize": pageSize,
|
||||
"TotalPages": common.PageCount(total, pageSize),
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "drafts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// WritePage 写文章页面
|
||||
func (ctrl *StudioController) WritePage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
// 支持编辑模式:传入 post_id 参数
|
||||
postIDStr := c.Query("id")
|
||||
if postIDStr != "" {
|
||||
id, err := strconv.ParseUint(postIDStr, 10, 64)
|
||||
if err == nil {
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err == nil {
|
||||
_, role, _ := common.GetGinUser(c)
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
}))
|
||||
return
|
||||
}
|
||||
c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "编辑文章 - 创作中心",
|
||||
"Post": post,
|
||||
"ActiveTab": "write",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "写文章 - 创作中心",
|
||||
"ActiveTab": "write",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// AnalyticsPage 数据分析页面
|
||||
func (ctrl *StudioController) AnalyticsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "数据分析 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "analytics",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "数据分析 - 创作中心",
|
||||
"Overview": overview,
|
||||
"ActiveTab": "analytics",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// ==============================
|
||||
// API 方法
|
||||
// ==============================
|
||||
|
||||
// OverviewAPI 创作中心数据概览
|
||||
func (ctrl *StudioController) OverviewAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取数据失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, overview)
|
||||
}
|
||||
|
||||
// ListPostsAPI 我的帖子列表(支持状态筛选)
|
||||
func (ctrl *StudioController) ListPostsAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, status, page, pageSize)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取列表失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, gin.H{
|
||||
"items": posts,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_pages": common.PageCount(total, pageSize),
|
||||
})
|
||||
}
|
||||
|
||||
// Create 创建/发布帖子
|
||||
func (ctrl *StudioController) Create(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
// LV0 用户不允许投稿
|
||||
if expVal, exists := c.Get("exp"); exists {
|
||||
if exp, ok := expVal.(int); ok && exp < 1 {
|
||||
common.Error(c, http.StatusForbidden, "经验不足,Lv1 解锁投稿")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var req model.PostCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "标题和正文不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.Create(uid, req.Title, req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "发布失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkWithMessage(c, post, "发布成功")
|
||||
}
|
||||
|
||||
// Update 编辑帖子
|
||||
func (ctrl *StudioController) Update(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req model.PostUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "标题和正文不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.Update(uint(id), req.Title, req.Body); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "编辑失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "编辑成功")
|
||||
}
|
||||
|
||||
// Delete 删除帖子
|
||||
func (ctrl *StudioController) Delete(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
authorID := post.UserID
|
||||
|
||||
if err := ctrl.postService.Delete(uint(id)); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
// 删稿扣作者域能(无视负数,有限重试后静默忽略)
|
||||
if ctrl.energySvc != nil {
|
||||
const maxRetries = 3
|
||||
backoff := 100 * time.Millisecond
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
if err := ctrl.energySvc.DeductOnDeletePost(authorID, uint(id)); err == nil {
|
||||
break
|
||||
}
|
||||
if i < maxRetries-1 {
|
||||
time.Sleep(backoff)
|
||||
backoff *= 2
|
||||
} else {
|
||||
log.Printf("删稿扣域能失败(user=%d, post=%d): %v", authorID, id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
common.OkMessage(c, "删除成功")
|
||||
}
|
||||
|
||||
// Submit 提交审核
|
||||
func (ctrl *StudioController) Submit(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "已提交审核")
|
||||
}
|
||||
|
||||
// TrendsAPI 创作中心趋势数据 API GET /api/studio/trends?period=7d|30d|90d
|
||||
func (ctrl *StudioController) TrendsAPI(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
if ctrl.trendsSvc == nil {
|
||||
common.Error(c, http.StatusInternalServerError, "趋势服务不可用")
|
||||
return
|
||||
}
|
||||
|
||||
period := c.DefaultQuery("period", "7d")
|
||||
var days int
|
||||
switch period {
|
||||
case "7d":
|
||||
days = 7
|
||||
case "30d":
|
||||
days = 30
|
||||
case "90d":
|
||||
days = 90
|
||||
default:
|
||||
common.Error(c, http.StatusBadRequest, "无效的时间范围,支持 7d/30d/90d")
|
||||
return
|
||||
}
|
||||
|
||||
since := time.Now().AddDate(0, 0, -days).Format("2006-01-02")
|
||||
|
||||
result, err := ctrl.trendsSvc.GetTrends(uid, since)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "获取趋势数据失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.Ok(c, result)
|
||||
}
|
||||
|
||||
114
internal/controller/studio_page_controller.go
Normal file
114
internal/controller/studio_page_controller.go
Normal file
@ -0,0 +1,114 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// OverviewPage 创作中心首页(数据概览)
|
||||
func (ctrl *StudioController) OverviewPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/overview.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "创作中心",
|
||||
"Error": "加载数据失败",
|
||||
"ActiveTab": "overview",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/overview.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "创作中心",
|
||||
"Overview": overview,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "overview",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// PostsPage 内容管理页
|
||||
func (ctrl *StudioController) PostsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
status := c.Query("status")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, status, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/posts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "内容管理 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "posts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
overview, _ := ctrl.postService.GetOverview(uid)
|
||||
|
||||
c.HTML(http.StatusOK, "studio/posts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "内容管理 - 创作中心",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"PageSize": pageSize,
|
||||
"TotalPages": common.PageCount(total, pageSize),
|
||||
"CurrentStatus": status,
|
||||
"Overview": overview,
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "posts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// DraftsPage 草稿箱页面
|
||||
func (ctrl *StudioController) DraftsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
|
||||
posts, total, err := ctrl.postService.ListByUser(uid, model.PostStatusDraft, page, pageSize)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/drafts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "草稿箱 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "drafts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/drafts.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "草稿箱 - 创作中心",
|
||||
"Posts": posts,
|
||||
"Total": total,
|
||||
"Page": page,
|
||||
"PageSize": pageSize,
|
||||
"TotalPages": common.PageCount(total, pageSize),
|
||||
"StatusNames": common.PostStatusDisplayNames,
|
||||
"ActiveTab": "drafts",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
80
internal/controller/studio_post_api_controller.go
Normal file
80
internal/controller/studio_post_api_controller.go
Normal file
@ -0,0 +1,80 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
"metazone.cc/metalab/internal/model"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Create 创建/发布帖子
|
||||
func (ctrl *StudioController) Create(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
// LV0 用户不允许投稿
|
||||
if expVal, exists := c.Get("exp"); exists {
|
||||
if exp, ok := expVal.(int); ok && exp < 1 {
|
||||
common.Error(c, http.StatusForbidden, "经验不足,Lv1 解锁投稿")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var req model.PostCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "标题和正文不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := ctrl.postService.Create(uid, req.Title, req.Body)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "发布失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkWithMessage(c, post, "发布成功")
|
||||
}
|
||||
|
||||
// Update 编辑帖子
|
||||
func (ctrl *StudioController) Update(c *gin.Context) {
|
||||
uid, role, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.Error(c, http.StatusUnauthorized, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req model.PostUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
common.Error(c, http.StatusBadRequest, "标题和正文不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
post, getErr := ctrl.postService.GetByID(uint(id))
|
||||
if getErr != nil {
|
||||
common.Error(c, http.StatusNotFound, "帖子不存在")
|
||||
return
|
||||
}
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
common.Error(c, http.StatusForbidden, "无权操作此帖子")
|
||||
return
|
||||
}
|
||||
|
||||
if err := ctrl.postService.Update(uint(id), req.Title, req.Body); err != nil {
|
||||
common.Error(c, http.StatusInternalServerError, "编辑失败")
|
||||
return
|
||||
}
|
||||
|
||||
common.OkMessage(c, "编辑成功")
|
||||
}
|
||||
77
internal/controller/studio_write_controller.go
Normal file
77
internal/controller/studio_write_controller.go
Normal file
@ -0,0 +1,77 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"metazone.cc/metalab/internal/common"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// WritePage 写文章页面
|
||||
func (ctrl *StudioController) WritePage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
// 支持编辑模式:传入 post_id 参数
|
||||
postIDStr := c.Query("id")
|
||||
if postIDStr != "" {
|
||||
id, err := strconv.ParseUint(postIDStr, 10, 64)
|
||||
if err == nil {
|
||||
post, err := ctrl.postService.GetByID(uint(id))
|
||||
if err == nil {
|
||||
_, role, _ := common.GetGinUser(c)
|
||||
if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
|
||||
c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "未找到",
|
||||
}))
|
||||
return
|
||||
}
|
||||
c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "编辑文章 - 创作中心",
|
||||
"Post": post,
|
||||
"ActiveTab": "write",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "写文章 - 创作中心",
|
||||
"ActiveTab": "write",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
|
||||
// AnalyticsPage 数据分析页面
|
||||
func (ctrl *StudioController) AnalyticsPage(c *gin.Context) {
|
||||
uid, _, ok := common.GetGinUser(c)
|
||||
if !ok {
|
||||
common.RedirectToLogin(c)
|
||||
return
|
||||
}
|
||||
|
||||
overview, err := ctrl.postService.GetOverview(uid)
|
||||
if err != nil {
|
||||
c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "数据分析 - 创作中心",
|
||||
"Error": "加载失败",
|
||||
"ActiveTab": "analytics",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
return
|
||||
}
|
||||
|
||||
c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
|
||||
"Title": "数据分析 - 创作中心",
|
||||
"Overview": overview,
|
||||
"ActiveTab": "analytics",
|
||||
"ExtraCSS": "/static/css/studio.css",
|
||||
}))
|
||||
}
|
||||
Reference in New Issue
Block a user