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(`` + htmlEscape(p.PlainText) + `
`) case domain.SubtitlePayload: b.WriteString(`♪ 音频:` + htmlEscape(p.Title) + `
` + htmlEscape(p.Question) + `