Skip to content

Commit

Permalink
support set visibility(public/private/friend) for post
Browse files Browse the repository at this point in the history
  • Loading branch information
alimy committed Jun 13, 2022
1 parent 087c6d2 commit 6f355c1
Show file tree
Hide file tree
Showing 20 changed files with 196 additions and 39 deletions.
3 changes: 3 additions & 0 deletions internal/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type DataService interface {
StickPost(post *model.Post) error
GetPostByID(id int64) (*model.Post, error)
GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error)
MergePosts(posts []*model.Post) ([]*model.PostFormated, error)
GetPostCount(conditions *model.ConditionsT) (int64, error)
UpdatePost(post *model.Post) error
GetUserPostStar(postID, userID int64) (*model.PostStar, error)
Expand Down Expand Up @@ -70,4 +71,6 @@ type DataService interface {
GetLatestPhoneCaptcha(phone string) (*model.Captcha, error)
UsePhoneCaptcha(captcha *model.Captcha) error
SendPhoneCaptcha(phone string) error

IsFriend(userID int64, friendID int64) bool
}
2 changes: 1 addition & 1 deletion internal/core/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import (
)

type IndexPostsService interface {
IndexPosts(offset int, limit int) ([]*model.PostFormated, error)
IndexPosts(userId int64, offset int, limit int) ([]*model.PostFormated, error)
}
6 changes: 4 additions & 2 deletions internal/core/search.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package core

import (
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/zinc"
)

Expand All @@ -12,8 +13,9 @@ const (
type SearchType string

type QueryT struct {
Query string
Type SearchType
Query string
Visibility []model.PostVisibleT
Type SearchType
}

// SearchService search service interface that implement base zinc
Expand Down
6 changes: 3 additions & 3 deletions internal/dao/cache_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ var (
errNotExist = errors.New("index posts cache not exist")
)

func newSimpleCacheIndexServant(getIndexPosts func(offset, limit int) ([]*model.PostFormated, error)) *simpleCacheIndexServant {
func newSimpleCacheIndexServant(getIndexPosts indexPostsFunc) *simpleCacheIndexServant {
s := conf.SimpleCacheIndexSetting
cacheIndex := &simpleCacheIndexServant{
getIndexPosts: getIndexPosts,
Expand Down Expand Up @@ -48,7 +48,7 @@ func newSimpleCacheIndexServant(getIndexPosts func(offset, limit int) ([]*model.
return cacheIndex
}

func (s *simpleCacheIndexServant) IndexPosts(offset int, limit int) ([]*model.PostFormated, error) {
func (s *simpleCacheIndexServant) IndexPosts(_userId int64, offset int, limit int) ([]*model.PostFormated, error) {
posts := s.atomicIndex.Load().([]*model.PostFormated)
end := offset + limit
size := len(posts)
Expand Down Expand Up @@ -78,7 +78,7 @@ func (s *simpleCacheIndexServant) startIndexPosts() {
case <-s.checkTick.C:
if len(s.indexPosts) == 0 {
logrus.Debugf("index posts by checkTick")
if s.indexPosts, err = s.getIndexPosts(0, s.maxIndexSize); err == nil {
if s.indexPosts, err = s.getIndexPosts(0, 0, s.maxIndexSize); err == nil {
s.atomicIndex.Store(s.indexPosts)
} else {
logrus.Errorf("get index posts err: %v", err)
Expand Down
3 changes: 2 additions & 1 deletion internal/dao/dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ type dataServant struct {
zinc *zinc.ZincClient
}

type indexPostsFunc func(int64, int, int) ([]*model.PostFormated, error)
type simpleCacheIndexServant struct {
getIndexPosts func(offset, limit int) ([]*model.PostFormated, error)
getIndexPosts indexPostsFunc
indexActionCh chan core.IndexActionT
indexPosts []*model.PostFormated
atomicIndex atomic.Value
Expand Down
12 changes: 7 additions & 5 deletions internal/dao/post_index.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import (
"github.com/sirupsen/logrus"
)

func (d *dataServant) IndexPosts(offset int, limit int) ([]*model.PostFormated, error) {
func (d *dataServant) IndexPosts(userId int64, offset int, limit int) ([]*model.PostFormated, error) {
if d.useCacheIndex {
if posts, err := d.cacheIndex.IndexPosts(offset, limit); err == nil {
if posts, err := d.cacheIndex.IndexPosts(userId, offset, limit); err == nil {
logrus.Debugln("get index posts from cached")
return posts, nil
}
}
logrus.Debugf("get index posts from database but useCacheIndex: %t", d.useCacheIndex)
return d.getIndexPosts(offset, limit)
return d.getIndexPosts(userId, offset, limit)
}

func (d *dataServant) MergePosts(posts []*model.Post) ([]*model.PostFormated, error) {
Expand Down Expand Up @@ -56,9 +56,11 @@ func (d *dataServant) MergePosts(posts []*model.Post) ([]*model.PostFormated, er
return postsFormated, nil
}

func (d *dataServant) getIndexPosts(offset int, limit int) ([]*model.PostFormated, error) {
// getIndexPosts _userId保留未来使用
func (d *dataServant) getIndexPosts(_userId int64, offset int, limit int) ([]*model.PostFormated, error) {
posts, err := (&model.Post{}).List(d.engine, &model.ConditionsT{
"ORDER": "is_top DESC, latest_replied_on DESC",
"visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend},
"ORDER": "is_top DESC, latest_replied_on DESC",
}, offset, limit)
if err != nil {
logrus.Debugf("getIndexPosts err: %v", err)
Expand Down
5 changes: 5 additions & 0 deletions internal/dao/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,8 @@ func (d *dataServant) SendPhoneCaptcha(phone string) error {
captchaModel.Create(d.engine)
return nil
}

func (d *dataServant) IsFriend(_userID int64, _friendID int64) bool {
// TODO: you are friend in all now
return true
}
33 changes: 33 additions & 0 deletions internal/middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,36 @@ func JWT() gin.HandlerFunc {
c.Next()
}
}

func JwtLoose() gin.HandlerFunc {
return func(c *gin.Context) {
token, exist := c.GetQuery("token")
if !exist {
token = c.GetHeader("Authorization")
// 验证前端传过来的token格式,不为空,开头为Bearer
if strings.HasPrefix(token, "Bearer ") {
// 验证通过,提取有效部分(除去Bearer)
token = token[7:]
} else {
c.Next()
}
}
if len(token) > 0 {
if claims, err := app.ParseToken(token); err == nil {
c.Set("UID", claims.UID)
c.Set("USERNAME", claims.Username)
// 加载用户信息
user := &model.User{
Model: &model.Model{
ID: claims.UID,
},
}
user, err := user.Get(conf.DBEngine)
if err == nil && (conf.JWTSetting.Issuer+":"+user.Salt) == claims.Issuer {
c.Set("USER", user)
}
}
}
c.Next()
}
}
35 changes: 23 additions & 12 deletions internal/model/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,30 @@ import (
"gorm.io/gorm"
)

// PostVisibleT 可访问类型,0公开,1私密,2好友
type PostVisibleT int

const (
PostVisitPublic PostVisibleT = iota
PostVisitPrivate
PostVisitFriend
)

type Post struct {
*Model
UserID int64 `json:"user_id"`
CommentCount int64 `json:"comment_count"`
CollectionCount int64 `json:"collection_count"`
UpvoteCount int64 `json:"upvote_count"`
IsTop int `json:"is_top"`
IsEssence int `json:"is_essence"`
IsLock int `json:"is_lock"`
LatestRepliedOn int64 `json:"latest_replied_on"`
Tags string `json:"tags"`
AttachmentPrice int64 `json:"attachment_price"`
IP string `json:"ip"`
IPLoc string `json:"ip_loc"`
UserID int64 `json:"user_id"`
CommentCount int64 `json:"comment_count"`
CollectionCount int64 `json:"collection_count"`
UpvoteCount int64 `json:"upvote_count"`
Visibility PostVisibleT `json:"visibility"`
IsTop int `json:"is_top"`
IsEssence int `json:"is_essence"`
IsLock int `json:"is_lock"`
LatestRepliedOn int64 `json:"latest_replied_on"`
Tags string `json:"tags"`
AttachmentPrice int64 `json:"attachment_price"`
IP string `json:"ip"`
IPLoc string `json:"ip_loc"`
}

type PostFormated struct {
Expand All @@ -31,6 +41,7 @@ type PostFormated struct {
CommentCount int64 `json:"comment_count"`
CollectionCount int64 `json:"collection_count"`
UpvoteCount int64 `json:"upvote_count"`
Visibility PostVisibleT `json:"visibility"`
IsTop int `json:"is_top"`
IsEssence int `json:"is_essence"`
IsLock int `json:"is_lock"`
Expand Down
3 changes: 2 additions & 1 deletion internal/routers/api/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func GetPostList(c *gin.Context) {
return
}
totalRows, _ := service.GetPostCount(&model.ConditionsT{
"ORDER": "latest_replied_on DESC",
"visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend},
"ORDER": "latest_replied_on DESC",
})

response.ToResponseList(posts, totalRows)
Expand Down
20 changes: 15 additions & 5 deletions internal/routers/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,13 +313,23 @@ func GetUserPosts(c *gin.Context) {
return
}

conditions := &model.ConditionsT{
"user_id": user.ID,
"ORDER": "latest_replied_on DESC",
visibilities := []model.PostVisibleT{model.PostVisitPublic}
if u, exists := c.Get("USER"); exists {
self := u.(*model.User)
if self.ID == user.ID || self.IsAdmin {
visibilities = append(visibilities, model.PostVisitPrivate, model.PostVisitFriend)
} else if service.IsFriend(user.ID, self.ID) {
visibilities = append(visibilities, model.PostVisitFriend)
}
}
conditions := model.ConditionsT{
"user_id": user.ID,
"visibility IN ?": visibilities,
"ORDER": "latest_replied_on DESC",
}

posts, err := service.GetPostList(&service.PostListReq{
Conditions: conditions,
Conditions: &conditions,
Offset: (app.GetPage(c) - 1) * app.GetPageSize(c),
Limit: app.GetPageSize(c),
})
Expand All @@ -328,7 +338,7 @@ func GetUserPosts(c *gin.Context) {
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
totalRows, _ := service.GetPostCount(conditions)
totalRows, _ := service.GetPostCount(&conditions)

response.ToResponseList(posts, totalRows)
}
Expand Down
6 changes: 5 additions & 1 deletion internal/routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,13 @@ func NewRouter() *gin.Engine {

// 获取用户基本信息
noAuthApi.GET("/user/profile", api.GetUserProfile)
}

// 宽松鉴权路由组
looseApi := r.Group("/").Use(middleware.JwtLoose())
{
// 获取用户动态列表
noAuthApi.GET("/user/posts", api.GetUserPosts)
looseApi.GET("/user/posts", api.GetUserPosts)
}

// 鉴权路由组
Expand Down
23 changes: 18 additions & 5 deletions internal/service/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type PostCreationReq struct {
Tags []string `json:"tags" binding:"required"`
Users []string `json:"users" binding:"required"`
AttachmentPrice int64 `json:"attachment_price"`
Visibility model.PostVisibleT `json:"visibility"`
}

type PostDelReq struct {
Expand Down Expand Up @@ -92,6 +93,7 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (*model.Pos
IP: ip,
IPLoc: util.GetIPLoc(ip),
AttachmentPrice: param.AttachmentPrice,
Visibility: param.Visibility,
}
post, err := ds.CreatePost(post)
if err != nil {
Expand Down Expand Up @@ -325,7 +327,7 @@ func GetPostContentByID(id int64) (*model.PostContent, error) {
}

func GetIndexPosts(offset int, limit int) ([]*model.PostFormated, error) {
return ds.IndexPosts(offset, limit)
return ds.IndexPosts(0, offset, limit)
}

func GetPostList(req *PostListReq) ([]*model.PostFormated, error) {
Expand Down Expand Up @@ -411,6 +413,11 @@ func GetPostListFromSearchByQuery(query string, offset, limit int) ([]*model.Pos
}

func PushPostToSearch(post *model.Post) {
// TODO: 暂时不索引私密文章,后续再完善
if post.Visibility == model.PostVisitPrivate {
return
}

indexName := conf.ZincSetting.Index

postFormated := post.Format()
Expand Down Expand Up @@ -447,6 +454,7 @@ func PushPostToSearch(post *model.Post) {
"comment_count": post.CommentCount,
"collection_count": post.CollectionCount,
"upvote_count": post.UpvoteCount,
"visibility": post.Visibility,
"is_top": post.IsTop,
"is_essence": post.IsEssence,
"content": contentFormated,
Expand All @@ -470,7 +478,9 @@ func DeleteSearchPost(post *model.Post) error {
func PushPostsToSearch(c *gin.Context) {
if ok, _ := conf.Redis.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
splitNum := 1000
totalRows, _ := GetPostCount(&model.ConditionsT{})
totalRows, _ := GetPostCount(&model.ConditionsT{
"visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend},
})

pages := math.Ceil(float64(totalRows) / float64(splitNum))
nums := int(pages)
Expand All @@ -483,9 +493,11 @@ func PushPostsToSearch(c *gin.Context) {
data := []map[string]interface{}{}

posts, _ := GetPostList(&PostListReq{
Conditions: &model.ConditionsT{},
Offset: i * splitNum,
Limit: splitNum,
Conditions: &model.ConditionsT{
"visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend},
},
Offset: i * splitNum,
Limit: splitNum,
})

for _, post := range posts {
Expand All @@ -508,6 +520,7 @@ func PushPostsToSearch(c *gin.Context) {
"comment_count": post.CommentCount,
"collection_count": post.CollectionCount,
"upvote_count": post.UpvoteCount,
"visibility": post.Visibility,
"is_top": post.IsTop,
"is_essence": post.IsEssence,
"content": contentFormated,
Expand Down
4 changes: 4 additions & 0 deletions internal/service/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,7 @@ func GetSuggestTags(keyword string) ([]string, error) {

return ts, nil
}

func IsFriend(userId, friendId int64) bool {
return ds.IsFriend(userId, friendId)
}
9 changes: 9 additions & 0 deletions scripts/migration/mysql/001-2206131310.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- ----------------------------
-- Table p_post alter add visibility column
-- ----------------------------
ALTER TABLE `p_post` ADD COLUMN `visibility` tinyint unsigned NOT NULL DEFAULT '0' COMMENT '可见性 0公开 1私密 2好友可见';

-- ----------------------------
-- Indexes structure for table p_post
-- ----------------------------
CREATE INDEX `idx_visibility` ON `p_post` ( `visibility` ) USING BTREE;
12 changes: 12 additions & 0 deletions scripts/migration/sqlite3/001-2206131310.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- ----------------------------
-- Table p_post alter add visibility column
-- ----------------------------
ALTER TABLE `p_post` ADD COLUMN `visibility` integer NOT NULL DEFAULT '0';

-- ----------------------------
-- Indexes structure for table p_post
-- ----------------------------
CREATE INDEX "main"."idx_visibility"
ON "p_post" (
"visibility" ASC
);
4 changes: 2 additions & 2 deletions web/build/info.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"version": "3",
"buildTime": "2022-06-08 23:29:43"
"version": "8",
"buildTime": "2022-06-13 17:16:22"
}
Loading

0 comments on commit 6f355c1

Please sign in to comment.