package api import ( "encoding/json" "net/http" "strings" "github.com/go-chi/chi/v5" "github.com/yourorg/article-platform/internal/domain" "github.com/yourorg/article-platform/internal/platform/auth" "github.com/yourorg/article-platform/internal/platform/httpx" "github.com/yourorg/article-platform/internal/platform/middleware" "github.com/yourorg/article-platform/internal/platform/rbac" ) // ── 个人资料与密码修改 ── type updateProfileReq struct { Nickname string `json:"nickname"` AvatarURL *string `json:"avatar_url"` Bio *string `json:"bio"` Gender *string `json:"gender"` Region *string `json:"region"` } func (d *Deps) updateProfile(w http.ResponseWriter, r *http.Request) { var req updateProfileReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } nickname := strings.TrimSpace(req.Nickname) if nickname == "" { httpx.WriteError(w, httpx.InvalidParam("昵称不能为空")) return } if strings.ContainsRune(nickname, '\uFFFD') { httpx.WriteError(w, httpx.InvalidParam("昵称包含非法编码或乱码字符")) return } uid := middleware.UserID(r.Context()) avatar := "" if req.AvatarURL != nil { avatar = *req.AvatarURL } bio := "" if req.Bio != nil { bio = *req.Bio } gender := "unknown" if req.Gender != nil { gender = *req.Gender } region := "" if req.Region != nil { region = *req.Region } if err := d.Users.UpdateProfile(r.Context(), d.Pool, uid, nickname, bio, avatar, gender, region); err != nil { httpx.WriteError(w, err) return } u, err := d.Users.GetByID(r.Context(), d.Pool, uid) if err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "ok": true, "user": u, "profile": u, }) } type updatePasswordReq struct { OldPassword string `json:"old_password"` NewPassword string `json:"new_password"` } func (d *Deps) updatePassword(w http.ResponseWriter, r *http.Request) { var req updatePasswordReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.OldPassword == "" || req.NewPassword == "" { httpx.WriteError(w, httpx.InvalidParam("原密码与新密码均不能为空")) return } if len(req.NewPassword) < 6 { httpx.WriteError(w, httpx.InvalidParam("新密码长度不能少于 6 位")) return } uid := middleware.UserID(r.Context()) hash, err := d.Users.GetPasswordHash(r.Context(), d.Pool, uid) if err != nil { httpx.WriteError(w, err) return } if err := auth.VerifyPassword(hash, req.OldPassword); err != nil { httpx.WriteError(w, httpx.NewError(http.StatusUnauthorized, httpx.CodeUnauthorized, "原密码输入错误")) return } newHash, err := auth.HashPassword(req.NewPassword) if err != nil { httpx.WriteError(w, err) return } if err := d.Users.UpdatePassword(r.Context(), d.Pool, uid, newHash); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "ok": true, "message": "密码修改成功", }) } // ── 个人中心 6 大列表接口 ── func (d *Deps) myFavorites(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListUserFavorites(r.Context(), d.Pool, uid, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) myLikes(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListUserLikes(r.Context(), d.Pool, uid, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) myFollowings(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListUserFollowings(r.Context(), d.Pool, uid, 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) myFollowersList(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListUserFollowers(r.Context(), d.Pool, uid, 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) myFollowedTopics(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListFollowedTopics(r.Context(), d.Pool, uid, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Topic{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) myHistory(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Interacts.ListViewHistory(r.Context(), d.Pool, uid, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Article{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) deleteHistoryItem(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) articleID := chi.URLParam(r, "articleID") if err := d.Interacts.DeleteViewHistory(r.Context(), d.Pool, uid, articleID); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) clearHistory(w http.ResponseWriter, r *http.Request) { uid := middleware.UserID(r.Context()) if err := d.Interacts.ClearViewHistory(r.Context(), d.Pool, uid); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 话题 (Topics) ── func (d *Deps) listTopics(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() sort := q.Get("sort") categoryID := q.Get("category_id") keyword := q.Get("keyword") uid := middleware.UserID(r.Context()) limit, offset := pageParams(r) items, total, err := d.Topics.List(r.Context(), d.Pool, sort, categoryID, keyword, uid, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Topic{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) getTopic(w http.ResponseWriter, r *http.Request) { topicID := chi.URLParam(r, "topicID") uid := middleware.UserID(r.Context()) topic, err := d.Topics.GetByID(r.Context(), d.Pool, topicID, uid) if err != nil { httpx.WriteError(w, err) return } // 前端直接读 res.data.name 等字段,话题对象平铺返回 httpx.WriteJSON(w, http.StatusOK, topic) } // followTopic 幂等切换关注状态(前端只有一个按钮,POST 即切换) func (d *Deps) followTopic(w http.ResponseWriter, r *http.Request) { topicID := chi.URLParam(r, "topicID") uid := middleware.UserID(r.Context()) following, err := d.Interacts.IsFollowingTopic(r.Context(), d.Pool, uid, topicID) if err != nil { httpx.WriteError(w, err) return } if following { if err := d.Interacts.UnfollowTopic(r.Context(), d.Pool, uid, topicID); err != nil { httpx.WriteError(w, err) return } } else { if err := d.Interacts.FollowTopic(r.Context(), d.Pool, uid, topicID); err != nil { httpx.WriteError(w, err) return } } var followCount int64 if err := d.Pool.QueryRow(r.Context(), `SELECT follow_count FROM topics WHERE id=$1`, topicID).Scan(&followCount); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "ok": true, "is_following": !following, "follow_count": followCount, }) } func (d *Deps) unfollowTopic(w http.ResponseWriter, r *http.Request) { topicID := chi.URLParam(r, "topicID") uid := middleware.UserID(r.Context()) if err := d.Interacts.UnfollowTopic(r.Context(), d.Pool, uid, topicID); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "is_followed": false}) } // 后台话题管理 func (d *Deps) adminListTopics(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() keyword := q.Get("keyword") categoryID := q.Get("category_id") limit, offset := pageParams(r) items, total, err := d.Topics.List(r.Context(), d.Pool, "new", categoryID, keyword, "", limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Topic{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } type adminTopicReq struct { Name string `json:"name"` Description *string `json:"description"` CoverURL *string `json:"cover_url"` CategoryID *string `json:"category_id"` Status string `json:"status"` } func (d *Deps) adminCreateTopic(w http.ResponseWriter, r *http.Request) { var req adminTopicReq 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 req.Status == "" { req.Status = "active" } uid := middleware.UserID(r.Context()) t := domain.Topic{ ID: newID(), Name: req.Name, Description: req.Description, CoverURL: req.CoverURL, CategoryID: req.CategoryID, Status: req.Status, CreatorID: &uid, } if err := d.Topics.Insert(r.Context(), d.Pool, &t); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusCreated, map[string]any{"ok": true, "topic": t}) } func (d *Deps) adminUpdateTopic(w http.ResponseWriter, r *http.Request) { topicID := chi.URLParam(r, "topicID") var req adminTopicReq 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 req.Status == "" { req.Status = "active" } t := domain.Topic{ ID: topicID, Name: req.Name, Description: req.Description, CoverURL: req.CoverURL, CategoryID: req.CategoryID, Status: req.Status, } if err := d.Topics.Update(r.Context(), d.Pool, &t); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) adminDeleteTopic(w http.ResponseWriter, r *http.Request) { topicID := chi.URLParam(r, "topicID") if err := d.Topics.Delete(r.Context(), d.Pool, topicID); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 模板 (Templates) ── func (d *Deps) listTemplates(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() category := q.Get("category") platform := q.Get("target_platform") limit, offset := pageParams(r) items, total, err := d.Templates.List(r.Context(), d.Pool, category, platform, limit, offset) if err != nil { httpx.WriteError(w, err) return } if items == nil { items = []domain.Template{} } httpx.WriteJSON(w, http.StatusOK, map[string]any{"items": items, "total": total}) } func (d *Deps) getTemplate(w http.ResponseWriter, r *http.Request) { templateID := chi.URLParam(r, "templateID") t, err := d.Templates.GetByID(r.Context(), d.Pool, templateID) if err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"template": t}) } type templateReq struct { Title string `json:"title"` Description *string `json:"description"` Category string `json:"category"` CoverURL *string `json:"cover_url"` TargetPlatform string `json:"target_platform"` Sections json.RawMessage `json:"sections"` // 数组形式(管理端) SectionsJSON json.RawMessage `json:"sections_json"` // JSON 字符串或数组(用户端) } // normalizeSections 统一 sections / sections_json 两种入参为 JSON 数组 func (req *templateReq) normalizeSections() json.RawMessage { if len(req.Sections) > 0 { return req.Sections } if len(req.SectionsJSON) > 0 { // sections_json 可能是 JSON 字符串包裹的数组 var s string if err := json.Unmarshal(req.SectionsJSON, &s); err == nil { return json.RawMessage(s) } return req.SectionsJSON } return json.RawMessage("[]") } func (d *Deps) createTemplate(w http.ResponseWriter, r *http.Request) { var req templateReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.Title == "" { httpx.WriteError(w, httpx.InvalidParam("标题不能为空")) return } if req.Category == "" { req.Category = "general" } if req.TargetPlatform == "" { req.TargetPlatform = "all" } secs := req.normalizeSections() t := domain.Template{ ID: newID(), Title: req.Title, Description: req.Description, Category: req.Category, CoverURL: req.CoverURL, TargetPlatform: req.TargetPlatform, SectionsJSON: secs, } if err := d.Templates.Insert(r.Context(), d.Pool, &t); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusCreated, map[string]any{"ok": true, "template": t}) } func (d *Deps) updateTemplate(w http.ResponseWriter, r *http.Request) { templateID := chi.URLParam(r, "templateID") var req templateReq if err := httpx.Decode(r, &req); err != nil { httpx.WriteError(w, err) return } if req.Title == "" { httpx.WriteError(w, httpx.InvalidParam("标题不能为空")) return } if req.Category == "" { req.Category = "general" } if req.TargetPlatform == "" { req.TargetPlatform = "all" } t := domain.Template{ ID: templateID, Title: req.Title, Description: req.Description, Category: req.Category, CoverURL: req.CoverURL, TargetPlatform: req.TargetPlatform, SectionsJSON: req.normalizeSections(), } if err := d.Templates.Update(r.Context(), d.Pool, &t); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) deleteTemplate(w http.ResponseWriter, r *http.Request) { templateID := chi.URLParam(r, "templateID") if err := d.Templates.Delete(r.Context(), d.Pool, templateID); err != nil { httpx.WriteError(w, err) return } httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } // ── 阅读记录与单篇数据看板 ── func (d *Deps) recordArticleView(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, err) return } uid := middleware.UserID(r.Context()) if uid != "" { _ = d.Interacts.RecordView(r.Context(), d.Pool, uid, a.ID) } // 递增计数 _, _ = d.Pool.Exec(r.Context(), "UPDATE articles SET view_count = view_count + 1 WHERE id = $1", a.ID) httpx.WriteJSON(w, http.StatusOK, map[string]any{"ok": true}) } func (d *Deps) articleStatsDetail(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, err) return } uid := middleware.UserID(r.Context()) if a.OwnerID != uid && !middleware.Role(r.Context()).AtLeast(rbac.RoleOperator) { httpx.WriteError(w, httpx.ErrForbidden) return } trends, err := d.Stats.GetArticleDailyTrend(r.Context(), d.Pool, a.ID, 7) if err != nil { httpx.WriteError(w, err) return } // 计算互动总量与互动率 totalInteractions := a.LikeCount + a.FavCount + a.CommentCount + a.ShareCount interactionRate := 0.0 if a.ViewCount > 0 { interactionRate = float64(totalInteractions) / float64(a.ViewCount) * 100 } httpx.WriteJSON(w, http.StatusOK, map[string]any{ "article": map[string]any{ "id": a.ID, "mask_id": a.MaskID, "title": a.Title, "cover_url": a.CoverImgURL, "published_at": a.PublishedAt, "status": a.Status, }, "metrics": map[string]any{ "view_count": a.ViewCount, "like_count": a.LikeCount, "fav_count": a.FavCount, "comment_count": a.CommentCount, "share_count": a.ShareCount, "total_interactions": totalInteractions, "interaction_rate": interactionRate, }, "daily_trends": trends, }) }