package api import ( "fmt" "net/http" "strings" "unicode/utf8" "github.com/go-chi/chi/v5" "github.com/yourorg/article-platform/internal/domain" "github.com/yourorg/article-platform/internal/platform/httpx" "github.com/yourorg/article-platform/internal/platform/middleware" "github.com/yourorg/article-platform/internal/repo" ) // ── 分类 / 标签 ── func (d *Deps) categoryTree(w http.ResponseWriter, r *http.Request) { tree, err := d.Taxonomy.ListCategories(r.Context(), d.Pool) if err != nil { httpx.WriteError(w, err) return } if tree == nil { tree = []domain.Category{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": tree}) } func (d *Deps) hotTags(w http.ResponseWriter, r *http.Request) { tags, err := d.Taxonomy.ListTags(r.Context(), d.Pool, 50) if err != nil { httpx.WriteError(w, err) return } if tags == nil { tags = []domain.Tag{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": tags}) } func (d *Deps) upsertTag(w http.ResponseWriter, r *http.Request) { var req struct { Name string `json:"name"` } if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } req.Name = strings.TrimSpace(req.Name) if req.Name == "" { httpx.WriteError(w, httpx.InvalidParam("标签名不能为空")) return } if err := d.Taxonomy.UpsertTag(r.Context(), d.Pool, newID(), req.Name); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) upsertCategory(w http.ResponseWriter, r *http.Request) { var req struct { Name string `json:"name"` Slug string `json:"slug"` ParentID *string `json:"parent_id,omitempty"` SortOrder int `json:"sort_order,omitempty"` } if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.Name == "" || req.Slug == "" { httpx.WriteError(w, httpx.InvalidParam("name 与 slug 均为必填")) return } if err := d.Taxonomy.UpsertCategory(r.Context(), d.Pool, newID(), req.Name, req.Slug, req.ParentID, req.SortOrder); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 搜索 ── // // 这里的 /search 是 PG 侧的兜底实现(trgm 索引 + ILIKE)。 // 生产环境的语义化中文搜索由 Meilisearch 承担,通过 search_outbox 同步索引。 // 保留这个接口的价值:搜索引擎故障时仍能降级返回结果。 func (d *Deps) search(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() keyword := strings.TrimSpace(q.Get("keyword")) if len([]rune(keyword)) > 64 { httpx.WriteError(w, httpx.InvalidParam("关键词过长")) return } if !utf8.ValidString(keyword) { httpx.WriteError(w, httpx.InvalidParam("关键词包含非法字符编码")) return } // keyword 为空时退化为按分类/排序浏览,供资讯流首屏使用 limit, _ := pageParams(r) items, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ Keyword: keyword, CategoryID: q.Get("categoryId"), Status: "published", Sort: q.Get("sort"), Cursor: q.Get("cursor"), Limit: limit, }) if err != nil { d.Log.Error("搜索失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } 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 != "", "engine": "postgres-trgm", }) } func (d *Deps) hotWords(w http.ResponseWriter, r *http.Request) { tags, err := d.Taxonomy.ListTags(r.Context(), d.Pool, 10) if err != nil { httpx.WriteError(w, err) return } words := make([]string, 0, len(tags)) for _, t := range tags { words = append(words, t.Name) } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": words}) } // searchSuggestions 返回搜索词建议。 // H5 客户端按 q 前缀匹配已发布文章标题,空 q 时回落为热门词。 func (d *Deps) searchSuggestions(w http.ResponseWriter, r *http.Request) { q := strings.TrimSpace(r.URL.Query().Get("q")) if q == "" { d.hotWords(w, r) return } if len([]rune(q)) > 64 || !utf8.ValidString(q) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": []string{}}) return } limit, _ := pageParams(r) items, _, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ Keyword: q, Status: "published", Sort: "latest", Limit: limit, }) if err != nil { d.Log.Error("搜索建议失败", "q", q, "err", err) httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": []string{}}) return } seen := make(map[string]bool, len(items)) words := make([]string, 0, limit) for _, a := range items { if a.Title == "" || seen[a.Title] { continue } seen[a.Title] = true words = append(words, a.Title) } // 美篇式联想:词不止来自文章标题,圈子名 / 用户昵称同样可被联想。 if len(words) < limit { circles, _, err := d.Topics.List(r.Context(), d.Pool, "hot", "", q, "", limit-len(words), 0) if err == nil { for _, t := range circles { if !seen[t.Name] { seen[t.Name] = true words = append(words, t.Name) } } } } if len(words) < limit { users, err := d.Users.SearchActiveUsers(r.Context(), d.Pool, q, limit-len(words)) if err == nil { for _, u := range users { if !seen[u.Nickname] { seen[u.Nickname] = true words = append(words, u.Nickname) } } } } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": words}) } // searchKeyword 校验并提取搜索关键词,非法时写错误响应并返回 false。 func searchKeyword(w http.ResponseWriter, r *http.Request) (string, bool) { keyword := strings.TrimSpace(r.URL.Query().Get("keyword")) if len([]rune(keyword)) > 64 { httpx.WriteError(w, httpx.InvalidParam("关键词过长")) return "", false } if !utf8.ValidString(keyword) { httpx.WriteError(w, httpx.InvalidParam("关键词包含非法字符编码")) return "", false } return keyword, true } // publicUser 搜索结果对外的用户公开资料。 // domain.User 的 JSON 里有 email/role/status 等内部字段, // 未登录可访问的搜索接口一律经此映射,避免泄露登录凭据与运营信息。 type publicUser struct { ID string `json:"id"` Account string `json:"account"` Nickname string `json:"nickname"` AvatarURL *string `json:"avatar_url,omitempty"` Bio *string `json:"bio,omitempty"` } func toPublicUsers(users []domain.User) []publicUser { out := make([]publicUser, 0, len(users)) for _, u := range users { out = append(out, publicUser{ ID: u.ID, Account: u.Account, Nickname: u.Nickname, AvatarURL: u.AvatarURL, Bio: u.Bio, }) } return out } // searchAll 美篇式「全部」Tab 的分区聚合:圈子、用户、文章一次返回。 // 每个分区各自截断到 limit,文章分区附带游标供「查看更多」接续。 func (d *Deps) searchAll(w http.ResponseWriter, r *http.Request) { keyword, ok := searchKeyword(w, r) if !ok { return } limit, _ := pageParams(r) users, err := d.Users.SearchActiveUsers(r.Context(), d.Pool, keyword, limit) if err != nil { d.Log.Error("搜索用户失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } circles, _, err := d.Topics.List(r.Context(), d.Pool, "hot", "", keyword, "", limit, 0) if err != nil { d.Log.Error("搜索圈子失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } articles, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ Keyword: keyword, Status: "published", Sort: r.URL.Query().Get("sort"), Limit: limit, }) if err != nil { d.Log.Error("搜索文章失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } pusers := toPublicUsers(users) if circles == nil { circles = []domain.Topic{} } if articles == nil { articles = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "users": pusers, "circles": circles, "articles": articles, "next_cursor": next, "has_more": next != "", "engine": "postgres-trgm", }) } // searchUsers 用户 Tab:只返回公开资料(publicUser),不含邮箱/角色/状态。 func (d *Deps) searchUsers(w http.ResponseWriter, r *http.Request) { keyword, ok := searchKeyword(w, r) if !ok { return } limit, _ := pageParams(r) users, err := d.Users.SearchActiveUsers(r.Context(), d.Pool, keyword, limit) if err != nil { d.Log.Error("搜索用户失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": toPublicUsers(users)}) } // searchCircles 圈子 Tab:按热度(文章数+关注数)排序的美友圈列表。 func (d *Deps) searchCircles(w http.ResponseWriter, r *http.Request) { keyword, ok := searchKeyword(w, r) if !ok { return } limit, _ := pageParams(r) circles, _, err := d.Topics.List(r.Context(), d.Pool, "hot", "", keyword, "", limit, 0) if err != nil { d.Log.Error("搜索圈子失败", "keyword", keyword, "err", err) httpx.WriteError(w, err) return } if circles == nil { circles = []domain.Topic{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": circles}) } // feedFollowing 好友圈动态流:关注的人 + 自己的已发布文章(朋友圈式)。 // 需登录;游标分页,cursor 为上一页最后一条的发布时间。 func (d *Deps) feedFollowing(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, _ := pageParams(r) items, next, err := d.Articles.FeedFollowing(r.Context(), d.Pool, uid, limit, r.URL.Query().Get("cursor")) if err != nil { d.Log.Error("好友圈动态流失败", "uid", uid, "err", err) httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "items": items, "next_cursor": next, "has_more": next != "", }) } // ── 分享与导出 ── func (d *Deps) shareArticle(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 } // 分享页只暴露已发布内容,草稿一律 403 if a.Status != domain.StatusPublished { httpx.WriteError(w, httpx.NewError(http.StatusForbidden, httpx.CodeForbidden, "文章未发布,无法分享")) return } secs, _ := d.Articles.ListSections(r.Context(), d.Pool, a.ID) a.Sections = secs d.Cache.IncrCounter(r.Context(), a.ID, "share", 1) httpx.WriteJSON(w, http.StatusOK, a) } // exportHTML 服务端渲染独立 HTML,可直接打印成 PDF 或用 Word 打开。 // 渲染逻辑独立实现,不依赖前端产物。 func (d *Deps) exportHTML(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.NewError(http.StatusForbidden, httpx.CodeForbidden, "文章未发布")) return } secs, _ := d.Articles.ListSections(r.Context(), d.Pool, a.ID) var b strings.Builder b.WriteString(``) b.WriteString(``) b.WriteString(``) b.WriteString(htmlEscape(a.Title)) b.WriteString(``) b.WriteString(`

` + htmlEscape(a.Title) + `

`) b.WriteString(`
`) if a.AuthorNickname != nil { b.WriteString(htmlEscape(*a.AuthorNickname)) } if a.PublishedAt != nil { b.WriteString(" · " + a.PublishedAt.Format("2006-01-02")) } b.WriteString(`
`) for _, s := range secs { renderSection(&b, s) } b.WriteString(``) name := sanitizeFilename(a.Title) + ".html" w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, "export.html", urlEnc(name))) w.Write([]byte(b.String())) } func renderSection(b *strings.Builder, s domain.Section) { v, err := s.Decoded() if err != nil { return } switch p := v.(type) { case domain.TextPayload: style := "" if p.TextAlign != "" { style = ` style="text-align:` + htmlEscape(p.TextAlign) + `"` } b.WriteString(`

` + htmlEscape(p.PlainText) + `

`) case domain.SubtitlePayload: b.WriteString(`

` + htmlEscape(p.Text) + `

`) case domain.ImagePayload: b.WriteString(`
`) for _, img := range p.Images { b.WriteString(`` + htmlEscape(img.Caption) + ``) if img.Caption != "" { b.WriteString(`
` + htmlEscape(img.Caption) + `
`) } } b.WriteString(`
`) case domain.VideoPayload: b.WriteString(`

▶ 视频:` + htmlEscape(p.Title) + `

`) case domain.AudioPayload: b.WriteString(`

♪ 音频:` + htmlEscape(p.Title) + `

`) case domain.VotePayload: b.WriteString(`

` + htmlEscape(p.Question) + `

    `) for _, o := range p.Options { b.WriteString(`
  1. ` + htmlEscape(o.Text) + `
  2. `) } b.WriteString(`
`) case domain.LocationPayload: b.WriteString(`
📍 ` + htmlEscape(p.Name)) if p.Address != "" { b.WriteString(` — ` + htmlEscape(p.Address)) } b.WriteString(`
`) case domain.GoodsPayload: b.WriteString(`
🛒 ` + htmlEscape(p.Title)) if p.PriceCent > 0 { b.WriteString(fmt.Sprintf(` ¥%.2f`, float64(p.PriceCent)/100)) } b.WriteString(`
`) } } func htmlEscape(s string) string { r := strings.NewReplacer( "&", "&", "<", "<", ">", ">", `"`, """, "'", "'", ) return r.Replace(s) } func sanitizeFilename(s string) string { r := strings.NewReplacer("/", "_", "\\", "_", ":", "_", "*", "_", "?", "_", `"`, "_", "<", "_", ">", "_", "|", "_", "\n", "_") out := r.Replace(s) if len([]rune(out)) > 60 { out = string([]rune(out)[:60]) } if out == "" { out = "article" } return out } func urlEnc(s string) string { var b strings.Builder for _, c := range []byte(s) { if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~' { b.WriteByte(c) } else { b.WriteString(fmt.Sprintf("%%%02X", c)) } } return b.String() } // ── 作者中心 ── func (d *Deps) myArticles(w http.ResponseWriter, r *http.Request) { limit, _ := pageParams(r) items, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ OwnerID: middleware.UserID(r.Context()), Status: r.URL.Query().Get("status"), ReviewStatus: r.URL.Query().Get("review_status"), Limit: limit, Cursor: r.URL.Query().Get("cursor"), }) 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}) } func (d *Deps) authorStats(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) draft, _ := d.Articles.Count(r.Context(), d.Pool, "draft", "") pending, _ := d.Articles.Count(r.Context(), d.Pool, "pending", "") published, _ := d.Articles.Count(r.Context(), d.Pool, "published", "") items, _, _ := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ OwnerID: uid, Status: "published", Limit: 100, }) var totalViews, totalLikes, totalFavs, totalComments int64 for _, a := range items { totalViews += a.ViewCount totalLikes += a.LikeCount totalFavs += a.FavCount totalComments += a.CommentCount } followers, _ := d.Interacts.FollowerCount(r.Context(), d.Pool, uid) httpx.WriteJSON(w, http.StatusOK, map[string]any{ "articles": map[string]int64{ "draft": draft, "pending": pending, "published": published, }, "totals": map[string]int64{ "views": totalViews, "likes": totalLikes, "favorites": totalFavs, "comments": totalComments, }, "followers": followers, }) } func (d *Deps) getUserArticles(w http.ResponseWriter, r *http.Request) { limit, _ := pageParams(r) items, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ OwnerID: chi.URLParam(r, "userID"), Status: "published", Limit: limit, Cursor: r.URL.Query().Get("cursor"), }) 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}) } // ── 举报 ── func (d *Deps) createReport(w http.ResponseWriter, r *http.Request) { var req struct { TargetType string `json:"target_type"` TargetID string `json:"target_id"` Reason string `json:"reason"` Description string `json:"description,omitempty"` } if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } switch req.TargetType { case "article", "comment", "user": default: httpx.WriteError(w, httpx.InvalidParam("target_type 取值非法")) return } if req.TargetID == "" || req.Reason == "" { httpx.WriteError(w, httpx.InvalidParam("target_id 与 reason 均为必填")) return } if err := d.Reports.Insert(r.Context(), d.Pool, newID(), middleware.UserID(r.Context()), req.TargetType, req.TargetID, req.Reason, req.Description); err != nil { httpx.WriteError(w, err) return } httpx.WriteCreated(w, map[string]any{"ok": true}) } func (d *Deps) listReports(w http.ResponseWriter, r *http.Request) { limit, offset := pageParams(r) items, total, err := d.Reports.List(r.Context(), d.Pool, r.URL.Query().Get("status"), r.URL.Query().Get("target_type"), limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []repo.ReportRow{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) handleReport(w http.ResponseWriter, r *http.Request) { var req struct { Note string `json:"note"` Status string `json:"status"` } if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.Status != "handled" && req.Status != "rejected" { httpx.WriteError(w, httpx.InvalidParam("status 只能是 handled 或 rejected")) return } if err := d.Reports.Handle(r.Context(), d.Pool, chi.URLParam(r, "reportID"), middleware.UserID(r.Context()), req.Note, req.Status); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 管理后台 ── func (d *Deps) adminOverview(w http.ResponseWriter, r *http.Request) { o, err := d.Stats.Overview(r.Context(), d.Pool) if err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, o) } func (d *Deps) adminTrends(w http.ResponseWriter, r *http.Request) { days := 30 if v := r.URL.Query().Get("days"); v != "" { fmt.Sscanf(v, "%d", &days) } pts, err := d.Stats.Trend(r.Context(), d.Pool, days) if err != nil { httpx.WriteError(w, err) return } if pts == nil { pts = []repo.TrendPoint{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": pts}) } func (d *Deps) adminListArticles(w http.ResponseWriter, r *http.Request) { limit, _ := pageParams(r) items, next, err := d.Articles.List(r.Context(), d.Pool, repo.ListParams{ Status: r.URL.Query().Get("status"), ReviewStatus: r.URL.Query().Get("review_status"), Keyword: r.URL.Query().Get("keyword"), Limit: limit, Cursor: r.URL.Query().Get("cursor"), }) 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}) } func (d *Deps) adminListUsers(w http.ResponseWriter, r *http.Request) { limit, offset := pageParams(r) items, total, err := d.Users.List(r.Context(), d.Pool, r.URL.Query().Get("keyword"), r.URL.Query().Get("role"), r.URL.Query().Get("status"), limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.User{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) adminSetUserStatus(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 } if req.Status != "active" && req.Status != "banned" { httpx.WriteError(w, httpx.InvalidParam("status 只能是 active 或 banned")) return } targetID := chi.URLParam(r, "userID") if targetID == middleware.UserID(r.Context()) { httpx.WriteError(w, httpx.InvalidParam("不能修改自己的账号状态")) return } if err := d.Users.SetStatus(r.Context(), d.Pool, targetID, req.Status); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "status": req.Status}) }