sky/internal/transport/http/article_handlers.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

1098 lines
30 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
"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/repo"
)
// ── 读 ──
func (d *Deps) getArticle(w http.ResponseWriter, r *http.Request) {
maskID := chi.URLParam(r, "maskID")
viewer := middleware.UserID(r.Context())
role := string(middleware.Role(r.Context()))
// 只有公开已发布文章才走缓存;作者看自己草稿、审核看待审必须实时。
// 用 singleflight + 逻辑过期读,避免热点文章在缓存过期的瞬间打穿数据库。
a, err := cache.GetOrLoad(r.Context(), d.Cache, cache.ArticleDetailKey(maskID),
func(ctx context.Context) (*domain.Article, error) {
art, err := d.Articles.GetByMaskID(ctx, d.Pool, maskID)
if err != nil {
if err == repo.ErrNotFound {
return nil, nil // 空值缓存,防穿透
}
return nil, err
}
secs, err := d.Articles.ListSections(ctx, d.Pool, art.ID)
if err != nil {
return nil, err
}
art.Sections = secs
tags, _ := d.Articles.ListTagsOfArticle(ctx, d.Pool, art.ID)
art.Tags = tags
// 用 PG 的值初始化实时计数器(只在 key 不存在时生效)
d.Cache.SeedCounters(ctx, art.ID, map[string]int64{
"view": art.ViewCount, "like": art.LikeCount,
"fav": art.FavCount, "comment": art.CommentCount,
"share": art.ShareCount,
})
return art, nil
})
if err != nil {
d.Log.Error("读取文章失败", "mask_id", maskID, "err", err)
httpx.WriteError(w, err)
return
}
if a == nil {
httpx.WriteError(w, httpx.NotFound("文章不存在"))
return
}
if !a.CanBeReadBy(viewer, role) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
// 覆盖为实时计数(PG 里的是定期落盘的快照,可能落后几十秒)
if cnt, err := d.Cache.Counters(r.Context(), a.ID); err == nil {
if v, ok := cnt["view"]; ok {
a.ViewCount = v
}
if v, ok := cnt["like"]; ok {
a.LikeCount = v
}
if v, ok := cnt["fav"]; ok {
a.FavCount = v
}
if v, ok := cnt["comment"]; ok {
a.CommentCount = v
}
}
// 浏览计数异步递增,绝不阻塞响应
d.Cache.IncrCounter(context.Background(), a.ID, "view", 1)
if a.CoverImgURL != nil {
a.CoverURL = a.CoverImgURL
}
// 详情缓存是跨用户共享的,用户态必须每次按当前登录者重新查,
// 绝不能塞进 cache.GetOrLoad 的闭包里,否则会串号。
d.fillViewerStates(r, []*domain.Article{a})
httpx.WriteJSON(w, http.StatusOK, a)
}
// fillViewerStates 为一批文章填充当前登录者的 is_liked / is_favorited / is_following。
// 未登录或查询失败时保持 false,不影响主响应。
func (d *Deps) fillViewerStates(r *http.Request, items []*domain.Article) {
if len(items) == 0 {
return
}
uid := middleware.UserID(r.Context())
if uid == "" {
return
}
articleIDs := make([]string, 0, len(items))
authorSet := make(map[string]struct{}, len(items))
for _, it := range items {
articleIDs = append(articleIDs, it.ID)
if it.OwnerID != "" {
authorSet[it.OwnerID] = struct{}{}
}
}
authorIDs := make([]string, 0, len(authorSet))
for id := range authorSet {
authorIDs = append(authorIDs, id)
}
liked, favorited, following, err := d.Interacts.ViewerStates(r.Context(), d.Pool, articleIDs, authorIDs, uid)
if err != nil {
d.Log.Error("查询互动状态失败", "err", err)
return
}
for _, it := range items {
it.IsLiked = liked[it.ID]
it.IsFavorited = favorited[it.ID]
it.IsFollowing = following[it.OwnerID]
}
}
func (d *Deps) listArticles(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
if limit <= 0 {
// 前端"我的文章"走 page_size 参数
limit, _ = strconv.Atoi(q.Get("page_size"))
}
p := repo.ListParams{
CategoryID: q.Get("category_id"),
TagID: q.Get("tag_id"),
Keyword: q.Get("keyword"),
Cursor: q.Get("cursor"),
Limit: limit,
}
if q.Get("mine") == "true" || q.Get("mine") == "1" {
// 我的文章:只看自己的(含草稿),必须登录。
// 之前这里忽略 mine 参数返回全站已发布文章,导致别人的文章
// 出现在"我的文章"列表里,点进编辑器后每次自动保存都 403。
uid := middleware.UserID(r.Context())
if uid == "" {
httpx.WriteError(w, httpx.ErrUnauthorized)
return
}
p.OwnerID = uid
switch s := q.Get("status"); s {
case "published", "draft", "reviewing":
p.Status = s
}
if q.Get("sort_by") == "updated_at" {
p.Sort = "updated"
}
} else {
// 公开列表只返回已发布
p.Status = "published"
p.Sort = q.Get("sort")
}
items, next, err := d.Articles.List(r.Context(), d.Pool, p)
if err != nil {
d.Log.Error("文章列表查询失败", "err", err)
httpx.WriteError(w, err)
return
}
if items == nil {
items = []domain.Article{}
}
for i := range items {
if items[i].CoverImgURL != nil {
items[i].CoverURL = items[i].CoverImgURL
}
}
ptrs := make([]*domain.Article, len(items))
for i := range items {
ptrs[i] = &items[i]
}
d.fillViewerStates(r, ptrs)
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"items": items,
"next_cursor": next,
"has_more": next != "",
})
}
func (d *Deps) listSections(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
}
secs, err := d.Articles.ListSections(r.Context(), d.Pool, a.ID)
if err != nil {
httpx.WriteError(w, err)
return
}
if secs == nil {
secs = []domain.Section{}
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": secs})
}
// ── 写 ──
type articleReq struct {
SchemaVersion int `json:"schema_version,omitempty"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Abstract string `json:"abstract,omitempty"`
CoverImgURL string `json:"cover_img_url,omitempty"`
CoverURL string `json:"cover_url,omitempty"`
CoverCrop string `json:"cover_crop,omitempty"`
CategoryID string `json:"category_id,omitempty"`
TagIDs []string `json:"tag_ids,omitempty"`
TopicID string `json:"topic_id,omitempty"`
Privacy string `json:"privacy,omitempty"`
Status string `json:"status,omitempty"`
MusicID string `json:"music_id,omitempty"`
FontID string `json:"font_id,omitempty"`
BgStyle string `json:"bg_style,omitempty"`
BgImgURL string `json:"bg_img_url,omitempty"`
VisualConfig json.RawMessage `json:"visual_config,omitempty"`
InteractionConfig json.RawMessage `json:"interaction_config,omitempty"`
EnableComment *bool `json:"enable_comment,omitempty"`
EnableWatermark *bool `json:"enable_watermark,omitempty"`
Sections []sectionReq `json:"sections,omitempty"`
}
type sectionReq struct {
ID string `json:"id,omitempty"`
Kind string `json:"kind"`
OrderIndex int `json:"order_index"`
Payload json.RawMessage `json:"payload"`
}
func isValidUUID(u string) bool {
if len(u) != 36 {
return false
}
for i, c := range u {
if i == 8 || i == 13 || i == 18 || i == 23 {
if c != '-' {
return false
}
} else {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
return false
}
}
}
return true
}
func (s *sectionReq) UnmarshalJSON(data []byte) error {
type Alias sectionReq
var aux struct {
Alias
Items json.RawMessage `json:"items,omitempty"`
Images json.RawMessage `json:"images,omitempty"`
Text string `json:"text,omitempty"`
PlainText string `json:"plain_text,omitempty"`
AST json.RawMessage `json:"ast,omitempty"`
URL string `json:"url,omitempty"`
VideoURL string `json:"video_url,omitempty"`
AudioURL string `json:"audio_url,omitempty"`
CoverURL string `json:"cover_url,omitempty"`
Question string `json:"question,omitempty"`
Options json.RawMessage `json:"options,omitempty"`
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
s.ID = aux.ID
s.Kind = aux.Kind
s.OrderIndex = aux.OrderIndex
s.Payload = aux.Payload
if len(s.Payload) == 0 || string(s.Payload) == "null" || string(s.Payload) == "{}" {
m := make(map[string]any)
switch domain.Kind(s.Kind) {
case domain.KindText:
pt := aux.PlainText
if pt == "" {
pt = aux.Text
}
m["plain_text"] = pt
if len(aux.AST) > 0 {
m["ast"] = aux.AST
}
m["text_align"] = "left"
case domain.KindSubtitle:
m["text"] = aux.Text
m["align"] = "left"
m["size"] = "md"
case domain.KindImage:
if len(aux.Images) > 0 {
m["images"] = aux.Images
} else if len(aux.Items) > 0 {
m["images"] = aux.Items
} else {
m["images"] = []any{}
}
m["layout"] = "single"
case domain.KindVideo:
vu := aux.VideoURL
if vu == "" {
vu = aux.URL
}
m["video_url"] = vu
m["cover_url"] = aux.CoverURL
case domain.KindAudio:
au := aux.AudioURL
if au == "" {
au = aux.URL
}
m["audio_url"] = au
m["title"] = aux.Text
case domain.KindVote:
m["question"] = aux.Question
if len(aux.Options) > 0 {
m["options"] = aux.Options
} else {
m["options"] = []any{}
}
default:
var full map[string]any
if err := json.Unmarshal(data, &full); err == nil {
delete(full, "id")
delete(full, "kind")
delete(full, "order_index")
delete(full, "payload")
m = full
}
}
if b, err := json.Marshal(m); err == nil {
s.Payload = b
}
} else if domain.Kind(s.Kind) == domain.KindImage {
var m map[string]any
if err := json.Unmarshal(s.Payload, &m); err == nil {
if _, ok := m["images"]; !ok {
if items, ok := m["items"]; ok {
m["images"] = items
if b, err := json.Marshal(m); err == nil {
s.Payload = b
}
}
}
}
}
return nil
}
func (d *Deps) createArticle(w http.ResponseWriter, r *http.Request) {
var req articleReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
if strings.TrimSpace(req.Title) == "" {
httpx.WriteError(w, httpx.InvalidParam("标题不能为空"))
return
}
if len([]rune(req.Title)) > 200 {
httpx.WriteError(w, httpx.InvalidParam("标题最多 200 字"))
return
}
secs := make([]domain.Section, 0, len(req.Sections))
for i, s := range req.Sections {
sec := domain.Section{
ID: idgen.NewUUIDv7(),
Kind: domain.Kind(s.Kind),
OrderIndex: i,
Payload: s.Payload,
}
if s.ID != "" && isValidUUID(s.ID) {
sec.ID = s.ID
}
if err := sec.Validate(); err != nil {
// 草稿允许空图片/小标题占位
isDraft := req.Status == "draft" || req.Status == ""
if isDraft && sec.Kind == domain.KindImage {
var ip domain.ImagePayload
if errDec := json.Unmarshal(sec.Payload, &ip); errDec == nil && len(ip.Images) == 0 {
secs = append(secs, sec)
continue
}
}
if isDraft && sec.Kind == domain.KindSubtitle {
var sp domain.SubtitlePayload
if errDec := json.Unmarshal(sec.Payload, &sp); errDec == nil && sp.Text == "" {
secs = append(secs, sec)
continue
}
}
httpx.WriteError(w, httpx.InvalidParam("第 "+strconv.Itoa(i+1)+" 个区块非法: "+err.Error()))
return
}
secs = append(secs, sec)
}
uid := middleware.UserID(r.Context())
now := time.Now().UTC()
initStatus := domain.StatusDraft
if req.Status == "published" {
initStatus = domain.StatusPublished
}
a := &domain.Article{
ID: idgen.NewUUIDv7(),
MaskID: idgen.MaskID("art"),
Title: req.Title,
Status: initStatus,
ReviewStatus: domain.ReviewPending,
OwnerID: uid,
Privacy: domain.PrivacyPublic,
EnableComment: true,
CreatedAt: now,
UpdatedAt: now,
VisualConfig: json.RawMessage("{}"),
InteractionConfig: json.RawMessage("{}"),
}
if req.Subtitle != "" {
a.Subtitle = &req.Subtitle
}
if req.Abstract != "" {
a.Abstract = &req.Abstract
}
coverURL := req.CoverImgURL
if coverURL == "" && req.CoverURL != "" {
coverURL = req.CoverURL
}
if coverURL != "" {
a.CoverImgURL = &coverURL
a.CoverURL = &coverURL
}
if req.CoverCrop != "" {
a.CoverCrop = json.RawMessage(strconv.Quote(req.CoverCrop))
}
if req.CategoryID != "" {
a.CategoryID = &req.CategoryID
}
if req.TopicID != "" {
a.TopicID = &req.TopicID
}
if req.Privacy != "" {
if !validPrivacy(req.Privacy) {
httpx.WriteError(w, httpx.InvalidParam("privacy 取值非法"))
return
}
a.Privacy = domain.Privacy(req.Privacy)
}
if req.EnableComment != nil {
a.EnableComment = *req.EnableComment
}
if req.EnableWatermark != nil {
a.EnableWatermark = *req.EnableWatermark
}
if len(req.VisualConfig) > 0 {
a.VisualConfig = req.VisualConfig
}
if len(req.InteractionConfig) > 0 {
a.InteractionConfig = req.InteractionConfig
}
if req.MusicID != "" {
a.MusicID = &req.MusicID
}
if req.FontID != "" {
a.FontID = &req.FontID
}
if req.BgStyle != "" {
a.BgStyle = &req.BgStyle
}
if req.BgImgURL != "" {
a.BgImgURL = &req.BgImgURL
}
err := d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
if err := d.Articles.Insert(r.Context(), tx, a); err != nil {
return err
}
for i := range secs {
secs[i].ArticleID = a.ID
if err := d.Articles.UpsertSection(r.Context(), tx, &secs[i]); err != nil {
return err
}
}
if len(req.TagIDs) > 0 {
if err := d.Articles.SetTags(r.Context(), tx, a.ID, req.TagIDs); err != nil {
return err
}
}
return d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert")
})
if err != nil {
d.Log.Error("创建文章失败", "err", err)
httpx.WriteError(w, err)
return
}
a.Sections = secs
if a.CoverImgURL != nil {
a.CoverURL = a.CoverImgURL
}
d.Cache.MarkStickyMaster(r.Context(), uid)
httpx.WriteCreated(w, a)
}
func validPrivacy(p string) bool {
switch p {
case "public", "private", "password", "paid":
return true
}
return false
}
func (d *Deps) updateArticle(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
var req articleReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
if req.Title != "" {
a.Title = req.Title
}
if req.Subtitle != "" {
a.Subtitle = &req.Subtitle
}
if req.Abstract != "" {
a.Abstract = &req.Abstract
}
coverURL := req.CoverImgURL
if coverURL == "" && req.CoverURL != "" {
coverURL = req.CoverURL
}
if coverURL != "" {
a.CoverImgURL = &coverURL
a.CoverURL = &coverURL
}
if req.CoverCrop != "" {
a.CoverCrop = json.RawMessage(strconv.Quote(req.CoverCrop))
}
if req.CategoryID != "" {
a.CategoryID = &req.CategoryID
}
if req.TopicID != "" {
a.TopicID = &req.TopicID
}
if req.Status == "published" {
a.Status = domain.StatusPublished
now := time.Now().UTC()
a.PublishedAt = &now
} else if req.Status == "draft" {
a.Status = domain.StatusDraft
}
if req.Privacy != "" {
if !validPrivacy(req.Privacy) {
httpx.WriteError(w, httpx.InvalidParam("privacy 取值非法"))
return
}
a.Privacy = domain.Privacy(req.Privacy)
}
if req.EnableComment != nil {
a.EnableComment = *req.EnableComment
}
if req.EnableWatermark != nil {
a.EnableWatermark = *req.EnableWatermark
}
if len(req.VisualConfig) > 0 {
a.VisualConfig = req.VisualConfig
}
if len(req.InteractionConfig) > 0 {
a.InteractionConfig = req.InteractionConfig
}
if req.MusicID != "" {
a.MusicID = &req.MusicID
}
if req.FontID != "" {
a.FontID = &req.FontID
}
if req.BgStyle != "" {
a.BgStyle = &req.BgStyle
}
if req.BgImgURL != "" {
a.BgImgURL = &req.BgImgURL
}
var newSecs []domain.Section
if req.Sections != nil {
newSecs = make([]domain.Section, 0, len(req.Sections))
for i, s := range req.Sections {
sec := domain.Section{
ID: idgen.NewUUIDv7(),
ArticleID: a.ID,
Kind: domain.Kind(s.Kind),
OrderIndex: i,
Payload: s.Payload,
}
if s.ID != "" && isValidUUID(s.ID) {
sec.ID = s.ID
}
if err := sec.Validate(); err != nil {
if sec.Kind == domain.KindImage {
var ip domain.ImagePayload
if errDec := json.Unmarshal(sec.Payload, &ip); errDec == nil && len(ip.Images) == 0 {
newSecs = append(newSecs, sec)
continue
}
}
if sec.Kind == domain.KindSubtitle {
var sp domain.SubtitlePayload
if errDec := json.Unmarshal(sec.Payload, &sp); errDec == nil && sp.Text == "" {
newSecs = append(newSecs, sec)
continue
}
}
if a.Status != domain.StatusDraft {
httpx.WriteError(w, httpx.InvalidParam("第 "+strconv.Itoa(i+1)+" 个区块非法: "+err.Error()))
return
}
}
newSecs = append(newSecs, sec)
}
}
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
if err := d.Articles.Update(r.Context(), tx, a); err != nil {
return err
}
if req.Sections != nil {
if err := d.Articles.ReplaceSections(r.Context(), tx, a.ID, newSecs); err != nil {
return err
}
}
if len(req.TagIDs) > 0 {
if err := d.Articles.SetTags(r.Context(), tx, a.ID, req.TagIDs); err != nil {
return err
}
}
return d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert")
})
if err != nil {
httpx.WriteError(w, err)
return
}
if req.Sections != nil {
a.Sections = newSecs
}
if a.CoverImgURL != nil {
a.CoverURL = a.CoverImgURL
}
// 失效所有相关缓存
d.Cache.Invalidate(r.Context(),
cache.ArticleDetailKey(a.MaskID),
cache.ArticleSecsKey(a.ID),
cache.ArticleMetaKey(a.ID),
)
d.invalidateFeeds(r, a.CategoryID)
d.Cache.MarkStickyMaster(r.Context(), middleware.UserID(r.Context()))
httpx.WriteJSON(w, http.StatusOK, a)
}
func (d *Deps) deleteArticle(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
if err := d.Articles.SoftDelete(r.Context(), d.Pool, a.ID); 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)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
}
func (d *Deps) publishArticle(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
// 发布前必须至少有一个区块,否则发布出去是空文章
secs, err := d.Articles.ListSections(r.Context(), d.Pool, a.ID)
if err != nil {
httpx.WriteError(w, err)
return
}
if len(secs) == 0 {
httpx.WriteError(w, httpx.InvalidParam("文章没有任何内容区块,不能发布"))
return
}
now := time.Now().UTC()
a.Status = domain.StatusPending
a.PublishedAt = &now
if err := d.Articles.UpdateStatus(r.Context(), d.Pool, a.ID, a.Status, domain.ReviewPending); err != nil {
httpx.WriteError(w, err)
return
}
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID))
d.invalidateFeeds(r, a.CategoryID)
d.Cache.MarkStickyMaster(r.Context(), middleware.UserID(r.Context()))
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"mask_id": a.MaskID, "status": a.Status, "message": "已提交审核",
})
}
// invalidateFeeds 用版本号失效整个 feed,绝不用 KEYS 扫描
func (d *Deps) invalidateFeeds(r *http.Request, categoryID *string) {
cats := []string{"all"}
if categoryID != nil {
cats = append(cats, *categoryID)
}
d.Cache.BumpFeedVersion(r.Context(), cats...)
}
// ── 区块写 ──
func (d *Deps) upsertSection(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
var req sectionReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
sec := domain.Section{
ID: req.ID,
ArticleID: a.ID,
Kind: domain.Kind(req.Kind),
OrderIndex: req.OrderIndex,
Payload: req.Payload,
}
if sec.ID == "" {
sec.ID = chi.URLParam(r, "sectionID")
}
if sec.ID == "" {
sec.ID = idgen.NewUUIDv7()
}
if err := sec.Validate(); err != nil {
httpx.WriteError(w, httpx.InvalidParam(err.Error()))
return
}
if err := d.Articles.UpsertSection(r.Context(), d.Pool, &sec); err != nil {
httpx.WriteError(w, err)
return
}
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
httpx.WriteJSON(w, http.StatusOK, sec)
}
func (d *Deps) deleteSection(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
if err := d.Articles.DeleteSection(r.Context(), d.Pool, a.ID, chi.URLParam(r, "sectionID")); err != nil {
httpx.WriteError(w, err)
return
}
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true})
}
type reorderReq struct {
SectionIDs []string `json:"section_ids"`
Order []string `json:"order,omitempty"`
}
func (d *Deps) reorderSections(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
var req reorderReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
ids := req.SectionIDs
if len(ids) == 0 && len(req.Order) > 0 {
ids = req.Order
}
if len(ids) == 0 {
httpx.WriteError(w, httpx.InvalidParam("section_ids 不能为空"))
return
}
var validIDs []string
for _, id := range ids {
if isValidUUID(id) {
validIDs = append(validIDs, id)
}
}
if len(validIDs) == 0 {
secs, _ := d.Articles.ListSections(r.Context(), d.Pool, a.ID)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": secs})
return
}
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
return d.Articles.ReorderSections(r.Context(), tx, a.ID, validIDs)
})
if err != nil {
httpx.WriteError(w, err)
return
}
d.Cache.Invalidate(r.Context(), cache.ArticleDetailKey(a.MaskID), cache.ArticleSecsKey(a.ID))
secs, _ := d.Articles.ListSections(r.Context(), d.Pool, a.ID)
httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": secs})
}
// ── 草稿快照处理器 ──
type saveDraftReq struct {
Title string `json:"title"`
Sections json.RawMessage `json:"sections"`
ClientSavedAt string `json:"client_saved_at"`
}
func (d *Deps) saveDraft(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
var req saveDraftReq
if err := httpx.Decode(r, &req); err != nil {
httpx.WriteError(w, err)
return
}
var clientSavedAt time.Time
if req.ClientSavedAt != "" {
if t, err := time.Parse(time.RFC3339, req.ClientSavedAt); err == nil {
clientSavedAt = t
}
}
// 正文区块解析提前到写库之前:格式非法时整单失败,不留「快照存了、正文没存」的半截状态
var newSecs []domain.Section
if len(req.Sections) > 0 {
var rawSecs []sectionReq
if err := json.Unmarshal(req.Sections, &rawSecs); err != nil {
httpx.WriteError(w, httpx.InvalidParam("区块数据格式非法"))
return
}
newSecs = make([]domain.Section, 0, len(rawSecs))
for i, s := range rawSecs {
sec := domain.Section{
ID: idgen.NewUUIDv7(),
ArticleID: a.ID,
Kind: domain.Kind(s.Kind),
OrderIndex: i,
Payload: s.Payload,
}
if s.ID != "" && isValidUUID(s.ID) {
sec.ID = s.ID
}
newSecs = append(newSecs, sec)
}
}
draftID := idgen.NewUUIDv7()
var item *repo.DraftItem
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
it, err := d.Articles.SaveDraft(r.Context(), tx, draftID, a.ID, req.Title, req.Sections, clientSavedAt)
if err != nil {
return err
}
item = it
// 主表正文必须跟随编辑内容:否则用户改完、离开、再进来看到的还是旧文章,
// 也就是「生成/已发布的文章无法二次编辑」。标题与区块一起落到主表,
// 已发布文章不因自动保存改动 status/review_status,只更新内容。
if req.Title != "" {
a.Title = req.Title
}
if err := d.Articles.Update(r.Context(), tx, a); err != nil {
return err
}
if len(newSecs) > 0 {
if err := d.Articles.ReplaceSections(r.Context(), tx, a.ID, newSecs); err != nil {
return err
}
}
return d.Outbox.Enqueue(r.Context(), tx, "article", a.ID, "upsert")
})
if err != nil {
d.Log.Error("保存草稿失败", "err", err)
httpx.WriteError(w, err)
return
}
d.Cache.Invalidate(r.Context(),
cache.ArticleDetailKey(a.MaskID),
cache.ArticleDetailKey(a.ID),
cache.ArticleSecsKey(a.ID),
cache.ArticleMetaKey(a.ID),
)
d.invalidateFeeds(r, a.CategoryID)
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"draft_id": item.ID,
"saved_at": item.CreatedAt,
})
}
func (d *Deps) listDrafts(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
items, err := d.Articles.ListDrafts(r.Context(), d.Pool, a.ID)
if err != nil {
httpx.WriteError(w, err)
return
}
httpx.WriteJSON(w, http.StatusOK, items)
}
func (d *Deps) getLatestDraft(w http.ResponseWriter, r *http.Request) {
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.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
item, err := d.Articles.GetLatestDraft(r.Context(), d.Pool, a.ID)
if err != nil {
if errors.Is(err, repo.ErrNotFound) {
httpx.WriteJSON(w, http.StatusOK, nil)
return
}
httpx.WriteError(w, err)
return
}
httpx.WriteJSON(w, http.StatusOK, item)
}
func (d *Deps) rollbackDraft(w http.ResponseWriter, r *http.Request) {
maskID := chi.URLParam(r, "maskID")
draftID := chi.URLParam(r, "draftID")
a, err := d.Articles.GetByMaskID(r.Context(), d.Pool, maskID)
if err != nil {
httpx.WriteError(w, httpx.NotFound("文章不存在"))
return
}
if !a.CanBeEditedBy(middleware.UserID(r.Context()), string(middleware.Role(r.Context()))) {
httpx.WriteError(w, httpx.ErrForbidden)
return
}
draft, err := d.Articles.GetDraftByID(r.Context(), d.Pool, draftID)
if err != nil {
httpx.WriteError(w, httpx.NotFound("草稿版本不存在"))
return
}
var rawSecs []sectionReq
if len(draft.SectionsJSON) > 0 {
_ = json.Unmarshal(draft.SectionsJSON, &rawSecs)
}
var newSecs []domain.Section
for i, s := range rawSecs {
sec := domain.Section{
ID: idgen.NewUUIDv7(),
ArticleID: a.ID,
Kind: domain.Kind(s.Kind),
OrderIndex: i,
Payload: s.Payload,
}
if s.ID != "" && isValidUUID(s.ID) {
sec.ID = s.ID
}
newSecs = append(newSecs, sec)
}
if draft.Title != "" {
a.Title = draft.Title
}
err = d.Articles.WithTx(r.Context(), func(tx pgx.Tx) error {
if err := d.Articles.Update(r.Context(), tx, a); err != nil {
return err
}
if len(newSecs) > 0 {
if err := d.Articles.ReplaceSections(r.Context(), tx, a.ID, newSecs); err != nil {
return err
}
}
return nil
})
if err != nil {
httpx.WriteError(w, err)
return
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{
"title": a.Title,
"sections": newSecs,
})
}