package api import ( "net/http" "strconv" "strings" "time" "unicode" "github.com/go-chi/chi/v5" "github.com/jackc/pgx/v5" "github.com/yourorg/article-platform/internal/domain" "github.com/yourorg/article-platform/internal/platform/cache" "github.com/yourorg/article-platform/internal/platform/httpx" "github.com/yourorg/article-platform/internal/platform/idgen" "github.com/yourorg/article-platform/internal/platform/middleware" "github.com/yourorg/article-platform/internal/platform/rbac" "github.com/yourorg/article-platform/internal/repo" ) // ── 点赞 / 收藏 ── // // 写路径全部走 Valkey 计数 + Set 去重,立即返回; // PG 落库由 worker 每 500ms 批量 flush。 // 绝不在请求里直接 UPDATE articles SET like_count = like_count + 1 —— 那是行锁地狱。 func (d *Deps) likeArticle(w http.ResponseWriter, r *http.Request) { d.toggleReaction(w, r, "like", true) } func (d *Deps) unlikeArticle(w http.ResponseWriter, r *http.Request) { d.toggleReaction(w, r, "like", false) } func (d *Deps) favoriteArticle(w http.ResponseWriter, r *http.Request) { d.toggleReaction(w, r, "fav", true) } func (d *Deps) unfavoriteArticle(w http.ResponseWriter, r *http.Request) { d.toggleReaction(w, r, "fav", false) } func (d *Deps) toggleReaction(w http.ResponseWriter, r *http.Request, kind string, on bool) { maskID := chi.URLParam(r, "maskID") a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, maskID) if err != nil { httpx.WriteError(w, httpx.NotFound("文章不存在")) return } if !a.CanBeReadBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) { httpx.WriteError(w, httpx.ErrForbidden) return } uid := middleware.UserID(r.Context()) // 先落库保证最终一致(幂等:ON CONFLICT DO NOTHING / DELETE) if kind == "like" { if on { err = d.Interacts.AddLike(r.Context(), d.Pool, a.ID, uid) } else { err = d.Interacts.RemoveLike(r.Context(), d.Pool, a.ID, uid) } } else { if on { err = d.Interacts.AddFavorite(r.Context(), d.Pool, a.ID, uid, "") } else { err = d.Interacts.RemoveFavorite(r.Context(), d.Pool, a.ID, uid) } } if err != nil { httpx.WriteError(w, err) return } // 再更新实时计数 delta := int64(1) if !on { delta = -1 } n, err := d.Cache.IncrCounter(r.Context(), a.ID, kind, delta) if err != nil { n = 0 } // 通知作者(自己给自己点赞不发通知) if on && a.OwnerID != uid { d.notify(r, a.OwnerID, uid, "like", "article", a.ID, "收到新的点赞", a.Title) } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "active": on, "count": n, }) } // ── 评论 ── // listComments 返回评论树:顶层评论分页,每个节点带自己的回复。 // // 分页只作用在顶层评论上(keyset 游标),回复跟着父级一起返回, // 所以翻页永远不会把一条讨论串切成两半 —— 这是与扁平列表的核心差异。 func (d *Deps) listComments(w http.ResponseWriter, r *http.Request) { a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, chi.URLParam(r, "maskID")) if err != nil { httpx.WriteError(w, httpx.NotFound("文章不存在")) return } if !a.CanBeReadBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) { httpx.WriteError(w, httpx.ErrForbidden) return } q := r.URL.Query() limit, _ := strconv.Atoi(q.Get("limit")) repliesLimit, _ := strconv.Atoi(q.Get("replies_limit")) cursorAt, cursorID := "", "" if c := q.Get("cursor"); c != "" { parts := strings.SplitN(c, "|", 2) if len(parts) == 2 { cursorAt, cursorID = parts[0], parts[1] } else { httpx.WriteError(w, httpx.InvalidParam("cursor 格式非法")) return } } threads, next, total, err := d.Comments.ListThreads(r.Context(), d.Pool, a.ID, limit, cursorAt, cursorID, repliesLimit) if err != nil { d.Log.Error("评论树查询失败", "article_id", a.ID, "err", err) httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "items": threads, "total": total, // 顶层评论总数 "next_cursor": next, "has_more": next != "", }) } // listReplies 懒加载某个顶层评论的全部回复。 // 前端在「查看全部 N 条回复」时调用。 func (d *Deps) listReplies(w http.ResponseWriter, r *http.Request) { rootID := chi.URLParam(r, "commentID") limit, offset := pageParams(r) items, total, err := d.Comments.ListReplies(r.Context(), d.Pool, rootID, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Comment{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "items": items, "total": total, "limit": limit, "offset": offset, "has_more": offset+len(items) < int(total), }) } type commentReq struct { Content string `json:"content"` ParentID string `json:"parent_id,omitempty"` } func (d *Deps) createComment(w http.ResponseWriter, r *http.Request) { a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, chi.URLParam(r, "maskID")) if err != nil { httpx.WriteError(w, httpx.NotFound("文章不存在")) return } if a.Status != domain.StatusPublished { httpx.WriteError(w, httpx.InvalidParam("文章未发布,不能评论")) return } if !a.EnableComment { httpx.WriteError(w, httpx.InvalidParam("该文章已关闭评论")) return } if !a.CanBeReadBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) { httpx.WriteError(w, httpx.ErrForbidden) return } var req commentReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } req.Content = trimSpace(req.Content) if len([]rune(req.Content)) == 0 { httpx.WriteError(w, httpx.InvalidParam("评论内容不能为空")) return } if len([]rune(req.Content)) > 5000 { httpx.WriteError(w, httpx.InvalidParam("评论最多 5000 字")) return } uid := middleware.UserID(r.Context()) c := &domain.Comment{ ID: idgen.NewUUIDv7(), ArticleID: a.ID, UserID: uid, Content: req.Content, Depth: 0, } parentOwner := "" if req.ParentID != "" { parentArticleID, parentDepth, err := d.Comments.GetParentDepth(r.Context(), d.Pool, req.ParentID) if err != nil { httpx.WriteError(w, httpx.InvalidParam("父评论不存在")) return } if parentArticleID != a.ID { httpx.WriteError(w, httpx.InvalidParam("父评论不属于该文章")) return } if parentDepth >= 3 { httpx.WriteError(w, httpx.InvalidParam("评论层级最多 3 层")) return } pid := req.ParentID c.ParentID = &pid c.Depth = parentDepth + 1 if pc, err := d.Comments.GetByID(r.Context(), d.Pool, req.ParentID); err == nil { parentOwner = pc.UserID } } if err := d.Comments.Insert(r.Context(), d.Pool, c); err != nil { httpx.WriteError(w, err) return } d.Cache.IncrCounter(r.Context(), a.ID, "comment", 1) // 通知:作者 + 被回复者(去重,别重复打扰) if a.OwnerID != uid { d.notify(r, a.OwnerID, uid, "comment", "article", a.ID, "收到新评论", req.Content) } if parentOwner != "" && parentOwner != uid && parentOwner != a.OwnerID { d.notify(r, parentOwner, uid, "reply", "comment", c.ID, "有人回复了你", req.Content) } httpx.WriteCreated(w, c) } func (d *Deps) deleteComment(w http.ResponseWriter, r *http.Request) { c, err := d.Comments.GetByID(r.Context(), d.Pool, chi.URLParam(r, "commentID")) if err != nil { httpx.WriteError(w, httpx.NotFound("评论不存在")) return } uid := middleware.UserID(r.Context()) role := middleware.Role(r.Context()) // 评论作者本人、文章作者、运营都能删 if c.UserID != uid && !rbac.Has(role, rbac.PermCommentManage) && !rbac.Has(role, rbac.PermCommentReview) { httpx.WriteError(w, httpx.ErrForbidden) return } if err := d.Comments.SetStatus(r.Context(), d.Pool, c.ID, "deleted"); err != nil { httpx.WriteError(w, err) return } d.Cache.IncrCounter(r.Context(), c.ArticleID, "comment", -1) httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) setCommentStatus(w http.ResponseWriter, r *http.Request) { var req struct { Status string `json:"status"` } if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } switch req.Status { case "visible", "hidden", "deleted": default: httpx.WriteError(w, httpx.InvalidParam("status 取值非法")) return } if err := d.Comments.SetStatus(r.Context(), d.Pool, chi.URLParam(r, "commentID"), req.Status); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) adminListComments(w http.ResponseWriter, r *http.Request) { limit, offset := pageParams(r) items, total, err := d.Comments.ListForAdmin(r.Context(), d.Pool, r.URL.Query().Get("status"), limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Comment{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } // ── 通知 ── // notify 写一条通知。真实生产环境应投递到 Valkey Stream 由 worker 批量写, // 这里在请求内直写以保证通知不丢;量级上来后换队列即可。 func (d *Deps) notify(r *http.Request, toUser, actorID, typ, entityType, entityID, title, content string) { n := domain.Notification{ ID: idgen.NewUUIDv7(), UserID: toUser, ActorID: &actorID, Type: typ, EntityType: entityType, EntityID: &entityID, Title: title, Content: truncate(content, 100), } if err := d.Notifs.InsertBatch(r.Context(), d.Pool, []domain.Notification{n}); err != nil { d.Log.Warn("通知写入失败", "to", toUser, "err", err) } } func (d *Deps) listNotifications(w http.ResponseWriter, r *http.Request) { limit, offset := pageParams(r) onlyUnread := r.URL.Query().Get("unread") == "1" items, total, err := d.Notifs.List(r.Context(), d.Pool, middleware.UserID(r.Context()), onlyUnread, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Notification{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) unreadCount(w http.ResponseWriter, r *http.Request) { n, err := d.Notifs.UnreadCount(r.Context(), d.Pool, middleware.UserID(r.Context())) if err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"unread": n}) } func (d *Deps) markRead(w http.ResponseWriter, r *http.Request) { var req struct { IDs []string `json:"ids,omitempty"` } _ = httpx.Decode(r, &req) // body 可为空,表示全部已读 if err := d.Notifs.MarkRead(r.Context(), d.Pool, middleware.UserID(r.Context()), req.IDs); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 关注 ── func (d *Deps) follow(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) target := chi.URLParam(r, "userID") if err := d.Interacts.Follow(r.Context(), d.Pool, uid, target); err != nil { httpx.WriteError(w, httpx.InvalidParam(err.Error())) return } d.notify(r, target, uid, "follow", "user", uid, "有人关注了你", "") httpx.WriteJSON(w, http.StatusOK, map[string]any{"following": true, "is_following": true}) } func (d *Deps) unfollow(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) target := chi.URLParam(r, "userID") if err := d.Interacts.Unfollow(r.Context(), d.Pool, uid, target); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"following": false, "is_following": false}) } // ── 审核 ── func (d *Deps) pendingReview(w http.ResponseWriter, r *http.Request) { limit, _ := pageParams(r) items, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ ReviewStatus: "pending", Limit: limit, }) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "next_cursor": next}) } type reviewReq struct { Note string `json:"note,omitempty"` } func (d *Deps) approveArticle(w http.ResponseWriter, r *http.Request) { d.doReview(w, r, true) } func (d *Deps) rejectArticle(w http.ResponseWriter, r *http.Request) { d.doReview(w, r, false) } func (d *Deps) doReview(w http.ResponseWriter, r *http.Request, approve bool) { a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, chi.URLParam(r, "maskID")) if err != nil { httpx.WriteError(w, httpx.NotFound("文章不存在")) return } var req reviewReq _ = httpx.Decode(r, &req) uid := middleware.UserID(r.Context()) now := time.Now().UTC() if approve { a.Status = domain.StatusPublished a.ReviewStatus = domain.ReviewApproved if a.PublishedAt == nil { a.PublishedAt = &now } } else { a.Status = domain.StatusDraft a.ReviewStatus = domain.ReviewRejected } a.ReviewNote = &req.Note a.ReviewedBy = &uid a.ReviewedAt = &now err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error { if err := d.Articles.Update(r.Context(), tx, a); err != nil { return err } return d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert") }) if err != nil { httpx.WriteError(w, err) return } d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID)) d.invalidateFeeds(r, a.CategoryID) verdict := "已通过审核" if !approve { verdict = "已驳回" } d.notify(r, a.OwnerID, uid, "review", "article", a.ID, "审核结果", verdict+":"+req.Note) httpx.WriteJSON(w, http.StatusOK, map[string]any{ "mask_id": a.MaskID, "status": a.Status, "review_status": a.ReviewStatus, }) } // ── 工具 ── // pageParams 解析分页参数。兼容三种调用习惯: // - page + size / page_size(frontend 与 admin 实际使用) // - limit + offset(内部调用) // // 返回 limit 与 offset。 func pageParams(r *http.Request) (int, int) { q := r.URL.Query() pick := func(keys ...string) string { for _, k := range keys { if v := q.Get(k); v != "" { return v } } return "" } limit, _ := strconv.Atoi(pick("size", "page_size", "limit")) if limit <= 0 || limit > 100 { limit = 20 } offset := 0 if v := pick("offset"); v != "" { offset, _ = strconv.Atoi(v) } if v := pick("page"); v != "" { if page, err := strconv.Atoi(v); err == nil && page > 1 { offset = (page - 1) * limit } } if offset < 0 { offset = 0 } return limit, offset } func trimSpace(s string) string { return strings.TrimFunc(s, func(r rune) bool { return unicode.IsSpace(r) || r == ' ' }) } func truncate(s string, n int) string { rs := []rune(s) if len(rs) <= n { return s } return string(rs[:n]) + "…" }