feat: 新增文章阅读量计数(已登录去重 + 访客防刷)

- Post 模型新增 ViewsCount 冗余计数字段
- 新建 PostReadLog 表(user_id + post_id 唯一索引),已登录用户每篇文章只计一次
- 新建 PostGuestReadLog 表(visitor_id + post_id 唯一索引),访客基于 Cookie 标识去重
- Repository 层新增 RecordRead / RecordGuestRead / IncrementViewsCount
- Service 层编排去重-计数逻辑,计数失败不影响页面渲染
- Controller 层 ShowPage + ShowAPI 触发计数,仅 approved 状态生效
- 双层防刷:唯一索引去重 + 2 秒冷却间隔
- 访客 Cookie (visitor_id) 基于 crypto/rand 生成,30 天有效期
This commit is contained in:
2026-06-02 00:02:48 +08:00
parent b869602185
commit b9d90fe7ec
8 changed files with 145 additions and 3 deletions

View File

@ -395,3 +395,21 @@ func (s *PostService) ListPendingRevisions(keyword string, page, pageSize int) (
func (s *PostService) IsPostAccessible(userID uint, role string, postUserID uint) bool {
return userID == postUserID || model.HasMinRole(role, model.RoleModerator)
}
// RecordRead 记录已登录用户阅读文章(已登录去重 + 防刷冷却)
func (s *PostService) RecordRead(userID, postID uint) {
firstRead, err := s.repo.RecordRead(userID, postID)
if err != nil || !firstRead {
return
}
_ = s.repo.IncrementViewsCount(postID)
}
// RecordGuestRead 记录访客阅读文章Cookie 标识去重 + 防刷冷却)
func (s *PostService) RecordGuestRead(visitorID string, postID uint) {
firstRead, err := s.repo.RecordGuestRead(visitorID, postID)
if err != nil || !firstRead {
return
}
_ = s.repo.IncrementViewsCount(postID)
}

View File

@ -41,6 +41,9 @@ type postStore interface {
Update(post *model.Post) error
SoftDelete(id uint) error
Restore(id uint) error
RecordRead(userID, postID uint) (bool, error)
RecordGuestRead(visitorID string, postID uint) (bool, error)
IncrementViewsCount(postID uint) error
}
// spaceUserStore SpaceService 所需的最小用户仓储接口