optimize code in internal/service pacakge

pull/42/head
alimy 3 years ago
parent a2f38fd1c5
commit 7221c6c3aa

@ -8,8 +8,10 @@ import (
"github.com/go-redis/redis/v8"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/logger"
"github.com/rocboss/paopao-ce/pkg/setting"
"github.com/rocboss/paopao-ce/pkg/zinc"
)
func init() {
@ -25,6 +27,8 @@ func init() {
if err != nil {
log.Fatalf("init.setupDBEngine err: %v", err)
}
client := zinc.NewClient(global.SearchSetting)
service.Initialize(global.DBEngine, client)
}
func setupSetting() error {

@ -70,7 +70,6 @@ func fileCheck(uploadType string, size int64) error {
func UploadAttachment(c *gin.Context) {
response := app.NewResponse(c)
svc := service.New(c)
uploadType := c.Request.FormValue("type")
file, fileHeader, err := c.Request.FormFile("file")
@ -153,9 +152,9 @@ func UploadAttachment(c *gin.Context) {
}
}
attachment, err = svc.CreateAttachment(attachment)
attachment, err = service.CreateAttachment(attachment)
if err != nil {
global.Logger.Errorf("svc.CreateAttachment err: %v", err)
global.Logger.Errorf("service.CreateAttachment err: %v", err)
response.ToErrorResponse(errcode.FileUploadFailed)
}
@ -164,21 +163,20 @@ func UploadAttachment(c *gin.Context) {
func DownloadAttachmentPrecheck(c *gin.Context) {
response := app.NewResponse(c)
svc := service.New(c)
contentID := convert.StrTo(c.Query("id")).MustInt64()
// 加载content
content, err := svc.GetPostContentByID(contentID)
content, err := service.GetPostContentByID(contentID)
if err != nil {
global.Logger.Errorf("svc.GetPostContentByID err: %v", err)
global.Logger.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
user, _ := c.Get("USER")
if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT {
// 加载post
post, err := svc.GetPost(content.PostID)
post, err := service.GetPost(content.PostID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v", err)
global.Logger.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
"paid": false,
})
@ -195,7 +193,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
// 检测是否有购买记录
response.ToResponse(gin.H{
"paid": svc.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID),
"paid": service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID),
})
return
}
@ -206,14 +204,13 @@ func DownloadAttachmentPrecheck(c *gin.Context) {
func DownloadAttachment(c *gin.Context) {
response := app.NewResponse(c)
svc := service.New(c)
contentID := convert.StrTo(c.Query("id")).MustInt64()
// 加载content
content, err := svc.GetPostContentByID(contentID)
content, err := service.GetPostContentByID(contentID)
if err != nil {
global.Logger.Errorf("svc.GetPostContentByID err: %v", err)
global.Logger.Errorf("service.GetPostContentByID err: %v", err)
response.ToErrorResponse(errcode.InvalidDownloadReq)
}
@ -222,9 +219,9 @@ func DownloadAttachment(c *gin.Context) {
user, _ := c.Get("USER")
// 加载post
post, err := svc.GetPost(content.PostID)
post, err := service.GetPost(content.PostID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v", err)
global.Logger.Errorf("service.GetPost err: %v", err)
response.ToResponse(gin.H{
"paid": false,
})
@ -239,13 +236,13 @@ func DownloadAttachment(c *gin.Context) {
}
// 检测是否有购买记录
if svc.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID) {
if service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID) {
paidFlag = true
}
if !paidFlag {
// 未购买,则尝试购买
err := svc.BuyPostAttachment(&model.Post{
err := service.BuyPostAttachment(&model.Post{
Model: &model.Model{
ID: post.ID,
},
@ -253,7 +250,7 @@ func DownloadAttachment(c *gin.Context) {
AttachmentPrice: post.AttachmentPrice,
}, user.(*model.User))
if err != nil {
global.Logger.Errorf("svc.BuyPostAttachment err: %v", err)
global.Logger.Errorf("service.BuyPostAttachment err: %v", err)
if err == errcode.InsuffientDownloadMoney {
response.ToErrorResponse(errcode.InsuffientDownloadMoney)

@ -11,15 +11,13 @@ import (
)
func GetPostComments(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
svc := service.New(c)
contents, totalRows, err := svc.GetPostComments(postID, "id ASC", 0, 0)
contents, totalRows, err := service.GetPostComments(postID, "id ASC", 0, 0)
if err != nil {
global.Logger.Errorf("svc.GetPostComments err: %v\n", err)
global.Logger.Errorf("service.GetPostComments err: %v\n", err)
response.ToErrorResponse(errcode.GetCommentsFailed)
return
}
@ -38,14 +36,13 @@ func CreatePostComment(c *gin.Context) {
}
userID, _ := c.Get("UID")
svc := service.New(c)
comment, err := svc.CreatePostComment(userID.(int64), param)
comment, err := service.CreatePostComment(c, userID.(int64), param)
if err != nil {
if err == errcode.MaxCommentCount {
response.ToErrorResponse(errcode.MaxCommentCount)
} else {
global.Logger.Errorf("svc.CreatePostComment err: %v\n", err)
global.Logger.Errorf("service.CreatePostComment err: %v\n", err)
response.ToErrorResponse(errcode.CreateCommentFailed)
}
return
@ -64,11 +61,10 @@ func DeletePostComment(c *gin.Context) {
return
}
user, _ := c.Get("USER")
svc := service.New(c)
comment, err := svc.GetPostComment(param.ID)
comment, err := service.GetPostComment(param.ID)
if err != nil {
global.Logger.Errorf("svc.GetPostComment err: %v\n", err)
global.Logger.Errorf("service.GetPostComment err: %v\n", err)
response.ToErrorResponse(errcode.GetCommentFailed)
return
}
@ -79,9 +75,9 @@ func DeletePostComment(c *gin.Context) {
}
// 执行删除
err = svc.DeletePostComment(comment)
err = service.DeletePostComment(comment)
if err != nil {
global.Logger.Errorf("svc.DeletePostComment err: %v\n", err)
global.Logger.Errorf("service.DeletePostComment err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
return
}
@ -99,11 +95,10 @@ func CreatePostCommentReply(c *gin.Context) {
return
}
user, _ := c.Get("USER")
svc := service.New(c)
comment, err := svc.CreatePostCommentReply(param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID)
comment, err := service.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID)
if err != nil {
global.Logger.Errorf("svc.CreatePostCommentReply err: %v\n", err)
global.Logger.Errorf("service.CreatePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.CreateReplyFailed)
return
}
@ -122,11 +117,10 @@ func DeletePostCommentReply(c *gin.Context) {
}
user, _ := c.Get("USER")
svc := service.New(c)
reply, err := svc.GetPostCommentReply(param.ID)
reply, err := service.GetPostCommentReply(param.ID)
if err != nil {
global.Logger.Errorf("svc.GetPostCommentReply err: %v\n", err)
global.Logger.Errorf("service.GetPostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.GetReplyFailed)
return
}
@ -137,9 +131,9 @@ func DeletePostCommentReply(c *gin.Context) {
}
// 执行删除
err = svc.DeletePostCommentReply(reply)
err = service.DeletePostCommentReply(reply)
if err != nil {
global.Logger.Errorf("svc.DeletePostCommentReply err: %v\n", err)
global.Logger.Errorf("service.DeletePostCommentReply err: %v\n", err)
response.ToErrorResponse(errcode.DeleteCommentFailed)
return
}

@ -30,12 +30,11 @@ func Version(c *gin.Context) {
func SyncSearchIndex(c *gin.Context) {
response := app.NewResponse(c)
svc := service.New(c)
user, _ := c.Get("USER")
if user.(*model.User).IsAdmin {
go svc.PushPostsToSearch()
go service.PushPostsToSearch(c)
}
response.ToResponse(nil)
@ -77,7 +76,6 @@ func PostCaptcha(c *gin.Context) {
response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
return
}
svc := service.New(c)
// 验证图片验证码
if res, err := global.Redis.Get(c.Request.Context(), "PaoPaoCaptcha:"+param.ImgCaptchaID).Result(); err != nil || res != param.ImgCaptcha {
@ -92,7 +90,7 @@ func PostCaptcha(c *gin.Context) {
return
}
err := svc.SendPhoneCaptcha(param.Phone)
err := service.SendPhoneCaptcha(c, param.Phone)
if err != nil {
global.Logger.Errorf("app.SendPhoneCaptcha errs: %v", errs)
response.ToErrorResponse(errcode.GetPhoneCaptchaError)

@ -16,9 +16,8 @@ func GetUnreadMsgCount(c *gin.Context) {
if u, exists := c.Get("USER"); exists {
user = u.(*model.User)
}
svc := service.New(c)
count, _ := svc.GetUnreadCount(user.ID)
count, _ := service.GetUnreadCount(user.ID)
response.ToResponse(gin.H{
"count": count,
@ -29,11 +28,10 @@ func GetMessages(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
svc := service.New(c)
messages, totalRows, err := svc.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
messages, totalRows, err := service.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("svc.GetMessages err: %v\n", err)
global.Logger.Errorf("service.GetMessages err: %v\n", err)
response.ToErrorResponse(errcode.GetMessagesFailed)
return
}
@ -52,10 +50,9 @@ func ReadMessage(c *gin.Context) {
}
userID, _ := c.Get("UID")
svc := service.New(c)
err := svc.ReadMessage(param.ID, userID.(int64))
err := service.ReadMessage(param.ID, userID.(int64))
if err != nil {
global.Logger.Errorf("svc.ReadMessage err: %v\n", err)
global.Logger.Errorf("service.ReadMessage err: %v\n", err)
response.ToErrorResponse(errcode.ReadMessageFailed)
return
}
@ -81,8 +78,7 @@ func SendUserWhisper(c *gin.Context) {
return
}
svc := service.New(c)
_, err := svc.CreateWhisper(&model.Message{
_, err := service.CreateWhisper(c, &model.Message{
SenderUserID: userID.(int64),
ReceiverUserID: param.UserID,
Type: model.MESSAGE_WHISPER,
@ -91,7 +87,7 @@ func SendUserWhisper(c *gin.Context) {
})
if err != nil {
global.Logger.Errorf("svc.CreateWhisper err: %v\n", err)
global.Logger.Errorf("service.CreateWhisper err: %v\n", err)
if err == errcode.TooManyWhisperNum {
response.ToErrorResponse(errcode.TooManyWhisperNum)

@ -22,10 +22,9 @@ func GetPostList(c *gin.Context) {
q.Type = "tag"
}
svc := service.New(c)
if q.Query == "" && q.Type == "search" {
// 直接读库
posts, err := svc.GetPostList(&service.PostListReq{
posts, err := service.GetPostList(&service.PostListReq{
Conditions: &model.ConditionsT{
"ORDER": "is_top DESC, latest_replied_on DESC",
},
@ -33,20 +32,20 @@ func GetPostList(c *gin.Context) {
Limit: app.GetPageSize(c),
})
if err != nil {
global.Logger.Errorf("svc.GetPostList err: %v\n", err)
global.Logger.Errorf("service.GetPostList err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
totalRows, _ := svc.GetPostCount(&model.ConditionsT{
totalRows, _ := service.GetPostCount(&model.ConditionsT{
"ORDER": "latest_replied_on DESC",
})
response.ToResponseList(posts, totalRows)
} else {
posts, totalRows, err := svc.GetPostListFromSearch(q, (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
posts, totalRows, err := service.GetPostListFromSearch(q, (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("svc.GetPostListFromSearch err: %v\n", err)
global.Logger.Errorf("service.GetPostListFromSearch err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
@ -58,11 +57,10 @@ func GetPost(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
svc := service.New(c)
postFormated, err := svc.GetPost(postID)
postFormated, err := service.GetPost(postID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v\n", err)
global.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -81,11 +79,10 @@ func CreatePost(c *gin.Context) {
}
userID, _ := c.Get("UID")
svc := service.New(c)
post, err := svc.CreatePost(userID.(int64), param)
post, err := service.CreatePost(c, userID.(int64), param)
if err != nil {
global.Logger.Errorf("svc.CreatePost err: %v\n", err)
global.Logger.Errorf("service.CreatePost err: %v\n", err)
response.ToErrorResponse(errcode.CreatePostFailed)
return
}
@ -104,12 +101,11 @@ func DeletePost(c *gin.Context) {
}
user, _ := c.Get("USER")
svc := service.New(c)
// 获取Post
postFormated, err := svc.GetPost(param.ID)
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v\n", err)
global.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -119,9 +115,9 @@ func DeletePost(c *gin.Context) {
return
}
err = svc.DeletePost(param.ID)
err = service.DeletePost(param.ID)
if err != nil {
global.Logger.Errorf("svc.DeletePost err: %v\n", err)
global.Logger.Errorf("service.DeletePost err: %v\n", err)
response.ToErrorResponse(errcode.DeletePostFailed)
return
}
@ -133,10 +129,9 @@ func GetPostStar(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
svc := service.New(c)
userID, _ := c.Get("UID")
_, err := svc.GetPostStar(postID, userID.(int64))
_, err := service.GetPostStar(postID, userID.(int64))
if err != nil {
response.ToResponse(gin.H{
"status": false,
@ -160,18 +155,17 @@ func PostStar(c *gin.Context) {
return
}
svc := service.New(c)
userID, _ := c.Get("UID")
status := false
star, err := svc.GetPostStar(param.ID, userID.(int64))
star, err := service.GetPostStar(param.ID, userID.(int64))
if err != nil {
// 创建Star
svc.CreatePostStar(param.ID, userID.(int64))
service.CreatePostStar(param.ID, userID.(int64))
status = true
} else {
// 取消Star
svc.DeletePostStar(star)
service.DeletePostStar(star)
}
response.ToResponse(gin.H{
@ -183,10 +177,9 @@ func GetPostCollection(c *gin.Context) {
postID := convert.StrTo(c.Query("id")).MustInt64()
response := app.NewResponse(c)
svc := service.New(c)
userID, _ := c.Get("UID")
_, err := svc.GetPostCollection(postID, userID.(int64))
_, err := service.GetPostCollection(postID, userID.(int64))
if err != nil {
response.ToResponse(gin.H{
"status": false,
@ -210,18 +203,17 @@ func PostCollection(c *gin.Context) {
return
}
svc := service.New(c)
userID, _ := c.Get("UID")
status := false
collection, err := svc.GetPostCollection(param.ID, userID.(int64))
collection, err := service.GetPostCollection(param.ID, userID.(int64))
if err != nil {
// 创建collection
svc.CreatePostCollection(param.ID, userID.(int64))
service.CreatePostCollection(param.ID, userID.(int64))
status = true
} else {
// 取消Star
svc.DeletePostCollection(collection)
service.DeletePostCollection(collection)
}
response.ToResponse(gin.H{
@ -240,12 +232,11 @@ func LockPost(c *gin.Context) {
}
user, _ := c.Get("USER")
svc := service.New(c)
// 获取Post
postFormated, err := svc.GetPost(param.ID)
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v\n", err)
global.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -254,9 +245,9 @@ func LockPost(c *gin.Context) {
response.ToErrorResponse(errcode.NoPermission)
return
}
err = svc.LockPost(param.ID)
err = service.LockPost(param.ID)
if err != nil {
global.Logger.Errorf("svc.LockPost err: %v\n", err)
global.Logger.Errorf("service.LockPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
return
}
@ -277,12 +268,11 @@ func StickPost(c *gin.Context) {
}
user, _ := c.Get("USER")
svc := service.New(c)
// 获取Post
postFormated, err := svc.GetPost(param.ID)
postFormated, err := service.GetPost(param.ID)
if err != nil {
global.Logger.Errorf("svc.GetPost err: %v\n", err)
global.Logger.Errorf("service.GetPost err: %v\n", err)
response.ToErrorResponse(errcode.GetPostFailed)
return
}
@ -291,9 +281,9 @@ func StickPost(c *gin.Context) {
response.ToErrorResponse(errcode.NoPermission)
return
}
err = svc.StickPost(param.ID)
err = service.StickPost(param.ID)
if err != nil {
global.Logger.Errorf("svc.StickPost err: %v\n", err)
global.Logger.Errorf("service.StickPost err: %v\n", err)
response.ToErrorResponse(errcode.LockPostFailed)
return
}
@ -313,11 +303,9 @@ func GetPostTags(c *gin.Context) {
return
}
svc := service.New(c)
tags, err := svc.GetPostTags(&param)
tags, err := service.GetPostTags(&param)
if err != nil {
global.Logger.Errorf("svc.GetPostTags err: %v\n", err)
global.Logger.Errorf("service.GetPostTags err: %v\n", err)
response.ToErrorResponse(errcode.GetPostTagsFailed)
return

@ -16,7 +16,7 @@ import (
"github.com/smartwalle/alipay/v3"
)
// 用户登录
// Login 用户登录
func Login(c *gin.Context) {
param := service.AuthRequest{}
response := app.NewResponse(c)
@ -27,10 +27,9 @@ func Login(c *gin.Context) {
return
}
svc := service.New(c)
user, err := svc.DoLogin(&param)
user, err := service.DoLogin(c, &param)
if err != nil {
global.Logger.Errorf("svc.DoLogin err: %v", err)
global.Logger.Errorf("service.DoLogin err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
@ -47,7 +46,7 @@ func Login(c *gin.Context) {
})
}
// 用户注册
// Register 用户注册
func Register(c *gin.Context) {
param := service.RegisterRequest{}
@ -59,31 +58,29 @@ func Register(c *gin.Context) {
return
}
svc := service.New(c)
// 用户名检查
err := svc.ValidUsername(param.Username)
err := service.ValidUsername(param.Username)
if err != nil {
global.Logger.Errorf("svc.Register err: %v", err)
global.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
// 密码检查
err = svc.CheckPassword(param.Password)
err = service.CheckPassword(param.Password)
if err != nil {
global.Logger.Errorf("svc.Register err: %v", err)
global.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
user, err := svc.Register(
user, err := service.Register(
param.Username,
param.Password,
)
if err != nil {
global.Logger.Errorf("svc.Register err: %v", err)
global.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(errcode.UserRegisterFailed)
return
}
@ -98,13 +95,12 @@ func Register(c *gin.Context) {
func GetUserInfo(c *gin.Context) {
param := service.AuthRequest{}
response := app.NewResponse(c)
svc := service.New(c)
if username, exists := c.Get("USERNAME"); exists {
param.Username = username.(string)
}
user, err := svc.GetUserInfo(&param)
user, err := service.GetUserInfo(&param)
if err != nil {
response.ToErrorResponse(errcode.UnauthorizedAuthNotExist)
@ -143,25 +139,23 @@ func ChangeUserPassword(c *gin.Context) {
user = u.(*model.User)
}
svc := service.New(c)
// 密码检查
err := svc.CheckPassword(param.Password)
err := service.CheckPassword(param.Password)
if err != nil {
global.Logger.Errorf("svc.Register err: %v", err)
global.Logger.Errorf("service.Register err: %v", err)
response.ToErrorResponse(err.(*errcode.Error))
return
}
// 旧密码校验
if !svc.ValidPassword(user.Password, param.OldPassword, user.Salt) {
if !service.ValidPassword(user.Password, param.OldPassword, user.Salt) {
response.ToErrorResponse(errcode.ErrorOldPassword)
return
}
// 更新入库
user.Password, user.Salt = svc.EncryptPasswordAndSalt(param.Password)
svc.UpdateUserInfo(user)
user.Password, user.Salt = service.EncryptPasswordAndSalt(param.Password)
service.UpdateUserInfo(user)
response.ToResponse(nil)
}
@ -181,7 +175,6 @@ func ChangeNickname(c *gin.Context) {
if u, exists := c.Get("USER"); exists {
user = u.(*model.User)
}
svc := service.New(c)
if utf8.RuneCountInString(param.Nickname) < 2 || utf8.RuneCountInString(param.Nickname) > 12 {
response.ToErrorResponse(errcode.NicknameLengthLimit)
@ -190,7 +183,7 @@ func ChangeNickname(c *gin.Context) {
// 执行绑定
user.Nickname = param.Nickname
svc.UpdateUserInfo(user)
service.UpdateUserInfo(user)
response.ToResponse(nil)
}
@ -210,7 +203,6 @@ func ChangeAvatar(c *gin.Context) {
if u, exists := c.Get("USER"); exists {
user = u.(*model.User)
}
svc := service.New(c)
if strings.Index(param.Avatar, "https://"+global.AliossSetting.AliossDomain) != 0 {
response.ToErrorResponse(errcode.InvalidParams)
@ -219,7 +211,7 @@ func ChangeAvatar(c *gin.Context) {
// 执行绑定
user.Avatar = param.Avatar
svc.UpdateUserInfo(user)
service.UpdateUserInfo(user)
response.ToResponse(nil)
}
@ -239,18 +231,17 @@ func BindUserPhone(c *gin.Context) {
if u, exists := c.Get("USER"); exists {
user = u.(*model.User)
}
svc := service.New(c)
// 手机重复性检查
if svc.CheckPhoneExist(user.ID, param.Phone) {
if service.CheckPhoneExist(user.ID, param.Phone) {
response.ToErrorResponse(errcode.ExistedUserPhone)
return
}
// 验证短信验证码
if !global.RuntimeSetting.DisablePhoneVerify {
if err := svc.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil {
global.Logger.Errorf("svc.CheckPhoneCaptcha err: %v\n", err)
if err := service.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil {
global.Logger.Errorf("service.CheckPhoneCaptcha err: %v\n", err)
response.ToErrorResponse(err)
return
}
@ -258,7 +249,7 @@ func BindUserPhone(c *gin.Context) {
// 执行绑定
user.Phone = param.Phone
svc.UpdateUserInfo(user)
service.UpdateUserInfo(user)
response.ToResponse(nil)
}
@ -267,10 +258,9 @@ func GetUserProfile(c *gin.Context) {
response := app.NewResponse(c)
username := c.Query("username")
svc := service.New(c)
user, err := svc.GetUserByUsername(username)
user, err := service.GetUserByUsername(username)
if err != nil {
global.Logger.Errorf("svc.GetUserByUsername err: %v\n", err)
global.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
return
}
@ -289,10 +279,9 @@ func GetUserPosts(c *gin.Context) {
response := app.NewResponse(c)
username := c.Query("username")
svc := service.New(c)
user, err := svc.GetUserByUsername(username)
user, err := service.GetUserByUsername(username)
if err != nil {
global.Logger.Errorf("svc.GetUserByUsername err: %v\n", err)
global.Logger.Errorf("service.GetUserByUsername err: %v\n", err)
response.ToErrorResponse(errcode.NoExistUsername)
return
}
@ -302,17 +291,17 @@ func GetUserPosts(c *gin.Context) {
"ORDER": "latest_replied_on DESC",
}
posts, err := svc.GetPostList(&service.PostListReq{
posts, err := service.GetPostList(&service.PostListReq{
Conditions: conditions,
Offset: (app.GetPage(c) - 1) * app.GetPageSize(c),
Limit: app.GetPageSize(c),
})
if err != nil {
global.Logger.Errorf("svc.GetPostList err: %v\n", err)
global.Logger.Errorf("service.GetPostList err: %v\n", err)
response.ToErrorResponse(errcode.GetPostsFailed)
return
}
totalRows, _ := svc.GetPostCount(conditions)
totalRows, _ := service.GetPostCount(conditions)
response.ToResponseList(posts, totalRows)
}
@ -321,11 +310,10 @@ func GetUserCollections(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
svc := service.New(c)
posts, totalRows, err := svc.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
posts, totalRows, err := service.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("svc.GetUserCollections err: %v\n", err)
global.Logger.Errorf("service.GetUserCollections err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -337,10 +325,9 @@ func GetUserStars(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
svc := service.New(c)
posts, totalRows, err := svc.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
posts, totalRows, err := service.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("svc.GetUserStars err: %v\n", err)
global.Logger.Errorf("service.GetUserStars err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -352,10 +339,9 @@ func GetSuggestUsers(c *gin.Context) {
keyword := c.Query("k")
response := app.NewResponse(c)
svc := service.New(c)
usernames, err := svc.GetSuggestUsers(keyword)
usernames, err := service.GetSuggestUsers(keyword)
if err != nil {
global.Logger.Errorf("svc.GetSuggestUsers err: %v\n", err)
global.Logger.Errorf("service.GetSuggestUsers err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -367,10 +353,9 @@ func GetSuggestTags(c *gin.Context) {
keyword := c.Query("k")
response := app.NewResponse(c)
svc := service.New(c)
tags, err := svc.GetSuggestTags(keyword)
tags, err := service.GetSuggestTags(keyword)
if err != nil {
global.Logger.Errorf("svc.GetSuggestTags err: %v\n", err)
global.Logger.Errorf("service.GetSuggestTags err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}
@ -390,10 +375,9 @@ func GetUserRechargeLink(c *gin.Context) {
// 下单
userID, _ := c.Get("UID")
svc := service.New(c)
recharge, err := svc.CreateRecharge(userID.(int64), param.Amount)
recharge, err := service.CreateRecharge(userID.(int64), param.Amount)
if err != nil {
global.Logger.Errorf("svc.CreateRecharge err: %v\n", err)
global.Logger.Errorf("service.CreateRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeReqFail)
return
@ -457,8 +441,7 @@ func GetUserRechargeResult(c *gin.Context) {
id := c.Query("id")
userID, _ := c.Get("UID")
svc := service.New(c)
recharge, err := svc.GetRechargeByID(convert.StrTo(id).MustInt64())
recharge, err := service.GetRechargeByID(convert.StrTo(id).MustInt64())
if err != nil {
response.ToErrorResponse(errcode.GetRechargeFailed)
return
@ -515,15 +498,14 @@ func AlipayNotify(c *gin.Context) {
return
}
svc := service.New(c)
id := c.Request.Form.Get("out_trade_no")
tradeNo := c.Request.Form.Get("trade_no")
tradeStatus := c.Request.Form.Get("trade_status")
if tradeStatus == "TRADE_SUCCESS" {
// 交易支付成功
err = svc.FinishRecharge(convert.StrTo(id).MustInt64(), tradeNo)
err = service.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo)
if err != nil {
global.Logger.Errorf("svc.FinishRecharge err: %v\n", err)
global.Logger.Errorf("service.FinishRecharge err: %v\n", err)
response.ToErrorResponse(errcode.RechargeNotifyError)
return
}
@ -535,11 +517,10 @@ func GetUserWalletBills(c *gin.Context) {
response := app.NewResponse(c)
userID, _ := c.Get("UID")
svc := service.New(c)
bills, totalRows, err := svc.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
bills, totalRows, err := service.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c))
if err != nil {
global.Logger.Errorf("svc.GetUserWalletBills err: %v\n", err)
global.Logger.Errorf("service.GetUserWalletBills err: %v\n", err)
response.ToErrorResponse(errcode.GetCollectionsFailed)
return
}

@ -2,6 +2,6 @@ package service
import "github.com/rocboss/paopao-ce/internal/model"
func (svc *Service) CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) {
return svc.dao.CreateAttachment(attachment)
func CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) {
return myDao.CreateAttachment(attachment)
}

@ -58,7 +58,7 @@ var defaultAvatars = []string{
"https://assets.paopao.info/public/avatar/default/abigail.png",
}
func (s *Service) GetRandomAvatar() string {
func GetRandomAvatar() string {
rand.Seed(time.Now().UnixMicro())
return defaultAvatars[rand.Intn(len(defaultAvatars))]
}

@ -4,6 +4,7 @@ import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
@ -28,12 +29,12 @@ type ReplyDelReq struct {
ID int64 `json:"id" binding:"required"`
}
func (svc *Service) GetPostComments(postID int64, sort string, offset, limit int) ([]*model.CommentFormated, int64, error) {
func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.CommentFormated, int64, error) {
conditions := &model.ConditionsT{
"post_id": postID,
"ORDER": sort,
}
comments, err := svc.dao.GetComments(conditions, offset, limit)
comments, err := myDao.GetComments(conditions, offset, limit)
if err != nil {
return nil, 0, err
@ -46,17 +47,17 @@ func (svc *Service) GetPostComments(postID int64, sort string, offset, limit int
commentIDs = append(commentIDs, comment.ID)
}
users, err := svc.dao.GetUsersByIDs(userIDs)
users, err := myDao.GetUsersByIDs(userIDs)
if err != nil {
return nil, 0, err
}
contents, err := svc.dao.GetCommentContentsByIDs(commentIDs)
contents, err := myDao.GetCommentContentsByIDs(commentIDs)
if err != nil {
return nil, 0, err
}
replies, err := svc.dao.GetCommentRepliesByID(commentIDs)
replies, err := myDao.GetCommentRepliesByID(commentIDs)
if err != nil {
return nil, 0, err
}
@ -84,14 +85,14 @@ func (svc *Service) GetPostComments(postID int64, sort string, offset, limit int
}
// 获取总量
totalRows, _ := svc.dao.GetCommentCount(conditions)
totalRows, _ := myDao.GetCommentCount(conditions)
return commentsFormated, totalRows, nil
}
func (svc *Service) CreatePostComment(userID int64, param CommentCreationReq) (*model.Comment, error) {
func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (*model.Comment, error) {
// 加载Post
post, err := svc.dao.GetPostByID(param.PostID)
post, err := myDao.GetPostByID(param.PostID)
if err != nil {
return nil, err
@ -100,14 +101,14 @@ func (svc *Service) CreatePostComment(userID int64, param CommentCreationReq) (*
if post.CommentCount >= global.AppSetting.MaxCommentCount {
return nil, errcode.MaxCommentCount
}
ip := svc.ctx.ClientIP()
ip := ctx.ClientIP()
comment := &model.Comment{
PostID: post.ID,
UserID: userID,
IP: ip,
IPLoc: util.GetIPLoc(ip),
}
comment, err = svc.dao.CreateComment(comment)
comment, err = myDao.CreateComment(comment)
if err != nil {
return nil, err
}
@ -127,21 +128,21 @@ func (svc *Service) CreatePostComment(userID int64, param CommentCreationReq) (*
Type: item.Type,
Sort: item.Sort,
}
svc.dao.CreateCommentContent(postContent)
myDao.CreateCommentContent(postContent)
}
// 更新Post回复数
post.CommentCount++
post.LatestRepliedOn = time.Now().Unix()
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
// 创建用户消息提醒
postMaster, err := svc.dao.GetUserByID(post.UserID)
postMaster, err := myDao.GetUserByID(post.UserID)
if err == nil && postMaster.ID != userID {
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: postMaster.ID,
Type: model.MESSAGE_COMMENT,
@ -151,13 +152,13 @@ func (svc *Service) CreatePostComment(userID int64, param CommentCreationReq) (*
})
}
for _, u := range param.Users {
user, err := svc.dao.GetUserByUsername(u)
user, err := myDao.GetUserByUsername(u)
if err != nil || user.ID == userID || user.ID == postMaster.ID {
continue
}
// 创建消息提醒
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
Type: model.MESSAGE_COMMENT,
@ -170,32 +171,32 @@ func (svc *Service) CreatePostComment(userID int64, param CommentCreationReq) (*
return comment, nil
}
func (svc *Service) GetPostComment(id int64) (*model.Comment, error) {
return svc.dao.GetCommentByID(id)
func GetPostComment(id int64) (*model.Comment, error) {
return myDao.GetCommentByID(id)
}
func (svc *Service) DeletePostComment(comment *model.Comment) error {
func DeletePostComment(comment *model.Comment) error {
// 加载post
post, err := svc.dao.GetPostByID(comment.PostID)
post, err := myDao.GetPostByID(comment.PostID)
if err == nil {
// 更新post回复数
post.CommentCount--
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
}
return svc.dao.DeleteComment(comment)
return myDao.DeleteComment(comment)
}
func (svc *Service) createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, *model.Comment, int64,
func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, *model.Comment, int64,
error) {
// 加载Comment
comment, err := svc.dao.GetCommentByID(commentID)
comment, err := myDao.GetCommentByID(commentID)
if err != nil {
return nil, nil, atUserID, err
}
// 加载comment的post
post, err := svc.dao.GetPostByID(comment.PostID)
post, err := myDao.GetPostByID(comment.PostID)
if err != nil {
return nil, nil, atUserID, err
}
@ -210,7 +211,7 @@ func (svc *Service) createPostPreHandler(commentID int64, userID, atUserID int64
if atUserID > 0 {
// 检测目前用户是否存在
users, _ := svc.dao.GetUsersByIDs([]int64{atUserID})
users, _ := myDao.GetUsersByIDs([]int64{atUserID})
if len(users) == 0 {
atUserID = 0
}
@ -219,18 +220,18 @@ func (svc *Service) createPostPreHandler(commentID int64, userID, atUserID int64
return post, comment, atUserID, nil
}
func (svc *Service) CreatePostCommentReply(commentID int64, content string, userID, atUserID int64) (*model.CommentReply, error) {
func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*model.CommentReply, error) {
var (
post *model.Post
comment *model.Comment
err error
)
if post, comment, atUserID, err = svc.createPostPreHandler(commentID, userID, atUserID); err != nil {
if post, comment, atUserID, err = createPostPreHandler(commentID, userID, atUserID); err != nil {
return nil, err
}
// 创建评论
ip := svc.ctx.ClientIP()
ip := ctx.ClientIP()
reply := &model.CommentReply{
CommentID: commentID,
UserID: userID,
@ -240,7 +241,7 @@ func (svc *Service) CreatePostCommentReply(commentID int64, content string, user
IPLoc: util.GetIPLoc(ip),
}
reply, err = svc.dao.CreateCommentReply(reply)
reply, err = myDao.CreateCommentReply(reply)
if err != nil {
return nil, err
}
@ -248,15 +249,15 @@ func (svc *Service) CreatePostCommentReply(commentID int64, content string, user
// 更新Post回复数
post.CommentCount++
post.LatestRepliedOn = time.Now().Unix()
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
// 创建用户消息提醒
commentMaster, err := svc.dao.GetUserByID(comment.UserID)
commentMaster, err := myDao.GetUserByID(comment.UserID)
if err == nil && commentMaster.ID != userID {
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: commentMaster.ID,
Type: model.MESSAGE_REPLY,
@ -266,9 +267,9 @@ func (svc *Service) CreatePostCommentReply(commentID int64, content string, user
ReplyID: reply.ID,
})
}
postMaster, err := svc.dao.GetUserByID(post.UserID)
postMaster, err := myDao.GetUserByID(post.UserID)
if err == nil && postMaster.ID != userID && commentMaster.ID != postMaster.ID {
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: postMaster.ID,
Type: model.MESSAGE_REPLY,
@ -279,10 +280,10 @@ func (svc *Service) CreatePostCommentReply(commentID int64, content string, user
})
}
if atUserID > 0 {
user, err := svc.dao.GetUserByID(atUserID)
user, err := myDao.GetUserByID(atUserID)
if err == nil && user.ID != userID && commentMaster.ID != user.ID && postMaster.ID != user.ID {
// 创建消息提醒
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
Type: model.MESSAGE_REPLY,
@ -297,24 +298,24 @@ func (svc *Service) CreatePostCommentReply(commentID int64, content string, user
return reply, nil
}
func (svc *Service) GetPostCommentReply(id int64) (*model.CommentReply, error) {
return svc.dao.GetCommentReplyByID(id)
func GetPostCommentReply(id int64) (*model.CommentReply, error) {
return myDao.GetCommentReplyByID(id)
}
func (svc *Service) DeletePostCommentReply(reply *model.CommentReply) error {
err := svc.dao.DeleteCommentReply(reply)
func DeletePostCommentReply(reply *model.CommentReply) error {
err := myDao.DeleteCommentReply(reply)
if err != nil {
return err
}
// 加载Comment
comment, err := svc.dao.GetCommentByID(reply.CommentID)
comment, err := myDao.GetCommentByID(reply.CommentID)
if err != nil {
return err
}
// 加载comment的post
post, err := svc.dao.GetPostByID(comment.PostID)
post, err := myDao.GetPostByID(comment.PostID)
if err != nil {
return err
}
@ -322,10 +323,10 @@ func (svc *Service) DeletePostCommentReply(reply *model.CommentReply) error {
// 更新Post回复数
post.CommentCount--
post.LatestRepliedOn = time.Now().Unix()
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
return nil
}

@ -4,13 +4,14 @@ import (
"fmt"
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/convert"
"github.com/rocboss/paopao-ce/pkg/errcode"
)
// 当日单用户私信总数限制TODO 配置化、积分兑换等)
// MAX_WHISPER_NUM_DAILY 当日单用户私信总数限制TODO 配置化、积分兑换等)
const MAX_WHISPER_NUM_DAILY = 20
type ReadMessageReq struct {
@ -21,37 +22,37 @@ type WhisperReq struct {
Content string `json:"content" binding:"required"`
}
// 创建私信
func (svc *Service) CreateWhisper(msg *model.Message) (*model.Message, error) {
// CreateWhisper 创建私信
func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) {
whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID)
// 今日频次限制
if res, _ := global.Redis.Get(svc.ctx, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY {
if res, _ := global.Redis.Get(c, whisperKey).Result(); convert.StrTo(res).MustInt() >= MAX_WHISPER_NUM_DAILY {
return nil, errcode.TooManyWhisperNum
}
// 创建私信
msg, err := svc.dao.CreateMessage(msg)
msg, err := myDao.CreateMessage(msg)
if err != nil {
return nil, err
}
// 写入当日(自然日)计数缓存
global.Redis.Incr(svc.ctx, whisperKey).Result()
global.Redis.Incr(c, whisperKey).Result()
currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
global.Redis.Expire(svc.ctx, whisperKey, endTime.Sub(currentTime))
global.Redis.Expire(c, whisperKey, endTime.Sub(currentTime))
return msg, err
}
func (svc *Service) GetUnreadCount(userID int64) (int64, error) {
return svc.dao.GetUnreadCount(userID)
func GetUnreadCount(userID int64) (int64, error) {
return myDao.GetUnreadCount(userID)
}
func (svc *Service) ReadMessage(id, userID int64) error {
func ReadMessage(id, userID int64) error {
// 获取message
message, err := svc.dao.GetMessageByID(id)
message, err := myDao.GetMessageByID(id)
if err != nil {
return err
}
@ -61,20 +62,20 @@ func (svc *Service) ReadMessage(id, userID int64) error {
}
// 已读消息
return svc.dao.ReadMessage(message)
return myDao.ReadMessage(message)
}
func (svc *Service) GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int64, error) {
func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int64, error) {
conditions := &model.ConditionsT{
"receiver_user_id": userID,
"ORDER": "id DESC",
}
messages, err := svc.dao.GetMessages(conditions, offset, limit)
messages, err := myDao.GetMessages(conditions, offset, limit)
for _, mf := range messages {
if mf.SenderUserID > 0 {
user, err := svc.dao.GetUserByID(mf.SenderUserID)
user, err := myDao.GetUserByID(mf.SenderUserID)
if err == nil {
mf.SenderUser = user.Format()
}
@ -82,17 +83,17 @@ func (svc *Service) GetMessages(userID int64, offset, limit int) ([]*model.Messa
}
if mf.PostID > 0 {
post, err := svc.GetPost(mf.PostID)
post, err := GetPost(mf.PostID)
if err == nil {
mf.Post = post
if mf.CommentID > 0 {
comment, err := svc.GetPostComment(mf.CommentID)
comment, err := GetPostComment(mf.CommentID)
if err == nil {
mf.Comment = comment
if mf.ReplyID > 0 {
reply, err := svc.GetPostCommentReply(mf.ReplyID)
reply, err := GetPostCommentReply(mf.ReplyID)
if err == nil {
mf.Reply = reply
}
@ -108,7 +109,7 @@ func (svc *Service) GetMessages(userID int64, offset, limit int) ([]*model.Messa
}
// 获取总量
totalRows, _ := svc.dao.GetMessageCount(conditions)
totalRows, _ := myDao.GetMessageCount(conditions)
return messages, totalRows, nil
}

@ -7,6 +7,7 @@ import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/dao"
"github.com/rocboss/paopao-ce/internal/model"
@ -39,18 +40,23 @@ type PostCreationReq struct {
type PostDelReq struct {
ID int64 `json:"id" binding:"required"`
}
type PostLockReq struct {
ID int64 `json:"id" binding:"required"`
}
type PostStickReq struct {
ID int64 `json:"id" binding:"required"`
}
type PostStarReq struct {
ID int64 `json:"id" binding:"required"`
}
type PostCollectionReq struct {
ID int64 `json:"id" binding:"required"`
}
type PostContentItem struct {
Content string `json:"content" binding:"required"`
Type model.PostContentT `json:"type" binding:"required"`
@ -76,8 +82,8 @@ func (p *PostContentItem) Check() error {
return nil
}
func (svc *Service) CreatePost(userID int64, param PostCreationReq) (*model.Post, error) {
ip := svc.ctx.ClientIP()
func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (*model.Post, error) {
ip := c.ClientIP()
post := &model.Post{
UserID: userID,
@ -86,7 +92,7 @@ func (svc *Service) CreatePost(userID int64, param PostCreationReq) (*model.Post
IPLoc: util.GetIPLoc(ip),
AttachmentPrice: param.AttachmentPrice,
}
post, err := svc.dao.CreatePost(post)
post, err := myDao.CreatePost(post)
if err != nil {
return nil, err
}
@ -97,7 +103,7 @@ func (svc *Service) CreatePost(userID int64, param PostCreationReq) (*model.Post
UserID: userID,
Tag: t,
}
svc.dao.CreateTag(tag)
myDao.CreateTag(tag)
}
for _, item := range param.Contents {
@ -117,21 +123,21 @@ func (svc *Service) CreatePost(userID int64, param PostCreationReq) (*model.Post
Type: item.Type,
Sort: item.Sort,
}
svc.dao.CreatePostContent(postContent)
myDao.CreatePostContent(postContent)
}
// 推送Search
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
// 创建用户消息提醒
for _, u := range param.Users {
user, err := svc.dao.GetUserByUsername(u)
user, err := myDao.GetUserByUsername(u)
if err != nil || user.ID == userID {
continue
}
// 创建消息提醒
go svc.dao.CreateMessage(&model.Message{
go myDao.CreateMessage(&model.Message{
SenderUserID: userID,
ReceiverUserID: user.ID,
Type: model.MESSAGE_POST,
@ -143,8 +149,8 @@ func (svc *Service) CreatePost(userID int64, param PostCreationReq) (*model.Post
return post, nil
}
func (svc *Service) DeletePost(id int64) error {
post, _ := svc.dao.GetPostByID(id)
func DeletePost(id int64) error {
post, _ := myDao.GetPostByID(id)
// tag删除
tags := strings.Split(post.Tags, ",")
@ -153,25 +159,25 @@ func (svc *Service) DeletePost(id int64) error {
tag := &model.Tag{
Tag: t,
}
svc.dao.DeleteTag(tag)
myDao.DeleteTag(tag)
}
err := svc.dao.DeletePost(post)
err := myDao.DeletePost(post)
if err != nil {
return err
}
// 删除索引
go svc.DeleteSearchPost(post)
go DeleteSearchPost(post)
return nil
}
func (svc *Service) LockPost(id int64) error {
post, _ := svc.dao.GetPostByID(id)
func LockPost(id int64) error {
post, _ := myDao.GetPostByID(id)
err := svc.dao.LockPost(post)
err := myDao.LockPost(post)
if err != nil {
return err
@ -180,10 +186,10 @@ func (svc *Service) LockPost(id int64) error {
return nil
}
func (svc *Service) StickPost(id int64) error {
post, _ := svc.dao.GetPostByID(id)
func StickPost(id int64) error {
post, _ := myDao.GetPostByID(id)
err := svc.dao.StickPost(post)
err := myDao.StickPost(post)
if err != nil {
return err
@ -192,109 +198,109 @@ func (svc *Service) StickPost(id int64) error {
return nil
}
func (svc *Service) GetPostStar(postID, userID int64) (*model.PostStar, error) {
return svc.dao.GetUserPostStar(postID, userID)
func GetPostStar(postID, userID int64) (*model.PostStar, error) {
return myDao.GetUserPostStar(postID, userID)
}
func (svc *Service) CreatePostStar(postID, userID int64) (*model.PostStar, error) {
func CreatePostStar(postID, userID int64) (*model.PostStar, error) {
// 加载Post
post, err := svc.dao.GetPostByID(postID)
post, err := myDao.GetPostByID(postID)
if err != nil {
return nil, err
}
star, err := svc.dao.CreatePostStar(postID, userID)
star, err := myDao.CreatePostStar(postID, userID)
if err != nil {
return nil, err
}
// 更新Post点赞数
post.UpvoteCount++
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
return star, nil
}
func (svc *Service) DeletePostStar(star *model.PostStar) error {
err := svc.dao.DeletePostStar(star)
func DeletePostStar(star *model.PostStar) error {
err := myDao.DeletePostStar(star)
if err != nil {
return err
}
// 加载Post
post, err := svc.dao.GetPostByID(star.PostID)
post, err := myDao.GetPostByID(star.PostID)
if err != nil {
return err
}
// 更新Post点赞数
post.UpvoteCount--
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
return nil
}
func (svc *Service) GetPostCollection(postID, userID int64) (*model.PostCollection, error) {
return svc.dao.GetUserPostCollection(postID, userID)
func GetPostCollection(postID, userID int64) (*model.PostCollection, error) {
return myDao.GetUserPostCollection(postID, userID)
}
func (svc *Service) CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) {
// 加载Post
post, err := svc.dao.GetPostByID(postID)
post, err := myDao.GetPostByID(postID)
if err != nil {
return nil, err
}
collection, err := svc.dao.CreatePostCollection(postID, userID)
collection, err := myDao.CreatePostCollection(postID, userID)
if err != nil {
return nil, err
}
// 更新Post点赞数
post.CollectionCount++
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
return collection, nil
}
func (svc *Service) DeletePostCollection(collection *model.PostCollection) error {
err := svc.dao.DeletePostCollection(collection)
func DeletePostCollection(collection *model.PostCollection) error {
err := myDao.DeletePostCollection(collection)
if err != nil {
return err
}
// 加载Post
post, err := svc.dao.GetPostByID(collection.PostID)
post, err := myDao.GetPostByID(collection.PostID)
if err != nil {
return err
}
// 更新Post点赞数
post.CollectionCount--
svc.dao.UpdatePost(post)
myDao.UpdatePost(post)
// 更新索引
go svc.PushPostToSearch(post)
go PushPostToSearch(post)
return nil
}
func (svc *Service) GetPost(id int64) (*model.PostFormated, error) {
post, err := svc.dao.GetPostByID(id)
func GetPost(id int64) (*model.PostFormated, error) {
post, err := myDao.GetPostByID(id)
if err != nil {
return nil, err
}
postContents, err := svc.dao.GetPostContentsByIDs([]int64{post.ID})
postContents, err := myDao.GetPostContentsByIDs([]int64{post.ID})
if err != nil {
return nil, err
}
users, err := svc.dao.GetUsersByIDs([]int64{post.UserID})
users, err := myDao.GetUsersByIDs([]int64{post.UserID})
if err != nil {
return nil, err
}
@ -312,21 +318,21 @@ func (svc *Service) GetPost(id int64) (*model.PostFormated, error) {
return postFormated, nil
}
func (svc *Service) GetPostContentByID(id int64) (*model.PostContent, error) {
return svc.dao.GetPostContentByID(id)
func GetPostContentByID(id int64) (*model.PostContent, error) {
return myDao.GetPostContentByID(id)
}
func (svc *Service) GetPostList(req *PostListReq) ([]*model.PostFormated, error) {
posts, err := svc.dao.GetPosts(req.Conditions, req.Offset, req.Limit)
func GetPostList(req *PostListReq) ([]*model.PostFormated, error) {
posts, err := myDao.GetPosts(req.Conditions, req.Offset, req.Limit)
if err != nil {
return nil, err
}
return svc.FormatPosts(posts)
return FormatPosts(posts)
}
func (svc *Service) FormatPosts(posts []*model.Post) ([]*model.PostFormated, error) {
func FormatPosts(posts []*model.Post) ([]*model.PostFormated, error) {
postIds := []int64{}
userIds := []int64{}
for _, post := range posts {
@ -334,12 +340,12 @@ func (svc *Service) FormatPosts(posts []*model.Post) ([]*model.PostFormated, err
userIds = append(userIds, post.UserID)
}
postContents, err := svc.dao.GetPostContentsByIDs(postIds)
postContents, err := myDao.GetPostContentsByIDs(postIds)
if err != nil {
return nil, err
}
users, err := svc.dao.GetUsersByIDs(userIds)
users, err := myDao.GetUsersByIDs(userIds)
if err != nil {
return nil, err
}
@ -366,17 +372,17 @@ func (svc *Service) FormatPosts(posts []*model.Post) ([]*model.PostFormated, err
return postsFormated, nil
}
func (svc *Service) GetPostCount(conditions *model.ConditionsT) (int64, error) {
return svc.dao.GetPostCount(conditions)
func GetPostCount(conditions *model.ConditionsT) (int64, error) {
return myDao.GetPostCount(conditions)
}
func (svc *Service) GetPostListFromSearch(q *dao.QueryT, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := svc.dao.QueryAll(q, global.SearchSetting.ZincIndex, offset, limit)
func GetPostListFromSearch(q *dao.QueryT, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := myDao.QueryAll(q, global.SearchSetting.ZincIndex, offset, limit)
if err != nil {
return nil, 0, err
}
posts, err := svc.FormatZincPost(queryResult)
posts, err := FormatZincPost(queryResult)
if err != nil {
return nil, 0, err
}
@ -384,13 +390,13 @@ func (svc *Service) GetPostListFromSearch(q *dao.QueryT, offset, limit int) ([]*
return posts, queryResult.Hits.Total.Value, nil
}
func (svc *Service) GetPostListFromSearchByQuery(query string, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := svc.dao.QuerySearch(global.SearchSetting.ZincIndex, query, offset, limit)
func GetPostListFromSearchByQuery(query string, offset, limit int) ([]*model.PostFormated, int64, error) {
queryResult, err := myDao.QuerySearch(global.SearchSetting.ZincIndex, query, offset, limit)
if err != nil {
return nil, 0, err
}
posts, err := svc.FormatZincPost(queryResult)
posts, err := FormatZincPost(queryResult)
if err != nil {
return nil, 0, err
}
@ -398,14 +404,14 @@ func (svc *Service) GetPostListFromSearchByQuery(query string, offset, limit int
return posts, queryResult.Hits.Total.Value, nil
}
func (svc *Service) PushPostToSearch(post *model.Post) {
func PushPostToSearch(post *model.Post) {
indexName := global.SearchSetting.ZincIndex
postFormated := post.Format()
postFormated.User = &model.UserFormated{
ID: post.UserID,
}
contents, _ := svc.dao.GetPostContentsByIDs([]int64{post.ID})
contents, _ := myDao.GetPostContentsByIDs([]int64{post.ID})
for _, content := range contents {
postFormated.Contents = append(postFormated.Contents, content.Format())
}
@ -446,31 +452,31 @@ func (svc *Service) PushPostToSearch(post *model.Post) {
"modified_on": post.ModifiedOn,
})
svc.dao.BulkPushDoc(data)
myDao.BulkPushDoc(data)
}
func (svc *Service) DeleteSearchPost(post *model.Post) error {
func DeleteSearchPost(post *model.Post) error {
indexName := global.SearchSetting.ZincIndex
return svc.dao.DelDoc(indexName, fmt.Sprintf("%d", post.ID))
return myDao.DelDoc(indexName, fmt.Sprintf("%d", post.ID))
}
func (svc *Service) PushPostsToSearch() {
if ok, _ := global.Redis.SetNX(svc.ctx, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
func PushPostsToSearch(c *gin.Context) {
if ok, _ := global.Redis.SetNX(c, "JOB_PUSH_TO_SEARCH", 1, time.Hour).Result(); ok {
splitNum := 1000
totalRows, _ := svc.GetPostCount(&model.ConditionsT{})
totalRows, _ := GetPostCount(&model.ConditionsT{})
pages := math.Ceil(float64(totalRows) / float64(splitNum))
nums := int(pages)
indexName := global.SearchSetting.ZincIndex
// 创建索引
svc.dao.CreateSearchIndex(indexName)
myDao.CreateSearchIndex(indexName)
for i := 0; i < nums; i++ {
data := []map[string]interface{}{}
posts, _ := svc.GetPostList(&PostListReq{
posts, _ := GetPostList(&PostListReq{
Conditions: &model.ConditionsT{},
Offset: i * splitNum,
Limit: splitNum,
@ -509,15 +515,15 @@ func (svc *Service) PushPostsToSearch() {
}
if len(data) > 0 {
svc.dao.BulkPushDoc(data)
myDao.BulkPushDoc(data)
}
}
global.Redis.Del(svc.ctx, "JOB_PUSH_TO_SEARCH")
global.Redis.Del(c, "JOB_PUSH_TO_SEARCH")
}
}
func (svc *Service) FormatZincPost(queryResult *zinc.QueryResultT) ([]*model.PostFormated, error) {
func FormatZincPost(queryResult *zinc.QueryResultT) ([]*model.PostFormated, error) {
posts := []*model.PostFormated{}
for _, hit := range queryResult.Hits.Hits {
item := &model.PostFormated{}
@ -535,12 +541,12 @@ func (svc *Service) FormatZincPost(queryResult *zinc.QueryResultT) ([]*model.Pos
postIds = append(postIds, post.ID)
userIds = append(userIds, post.UserID)
}
postContents, err := svc.dao.GetPostContentsByIDs(postIds)
postContents, err := myDao.GetPostContentsByIDs(postIds)
if err != nil {
return nil, err
}
users, err := svc.dao.GetUsersByIDs(userIds)
users, err := myDao.GetUsersByIDs(userIds)
if err != nil {
return nil, err
}
@ -565,7 +571,7 @@ func (svc *Service) FormatZincPost(queryResult *zinc.QueryResultT) ([]*model.Pos
return posts, nil
}
func (svc *Service) GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) {
func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) {
num := param.Num
if num > global.AppSetting.MaxPageSize {
num = global.AppSetting.MaxPageSize
@ -585,7 +591,7 @@ func (svc *Service) GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error
}
}
tags, err := svc.dao.GetTags(conditions, 0, num)
tags, err := myDao.GetTags(conditions, 0, num)
if err != nil {
return nil, err
}
@ -596,7 +602,7 @@ func (svc *Service) GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error
userIds = append(userIds, tag.UserID)
}
users, _ := svc.dao.GetUsersByIDs(userIds)
users, _ := myDao.GetUsersByIDs(userIds)
tagsFormated := []*model.TagFormated{}
for _, tag := range tags {
@ -612,8 +618,8 @@ func (svc *Service) GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error
return tagsFormated, nil
}
func (svc *Service) CheckPostAttachmentIsPaid(postID, userID int64) bool {
bill, err := svc.dao.GetPostAttatchmentBill(postID, userID)
func CheckPostAttachmentIsPaid(postID, userID int64) bool {
bill, err := myDao.GetPostAttatchmentBill(postID, userID)
return err == nil && bill.Model != nil && bill.ID > 0
}

@ -1,26 +1,15 @@
package service
import (
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/dao"
"github.com/rocboss/paopao-ce/pkg/zinc"
"gorm.io/gorm"
)
type Service struct {
ctx *gin.Context
dao *dao.Dao
}
func New(ctx *gin.Context) Service {
svc := Service{ctx: ctx}
svc.dao = dao.New(global.DBEngine, &zinc.ZincClient{
ZincClientConfig: &zinc.ZincClientConfig{
ZincHost: global.SearchSetting.ZincHost,
ZincUser: global.SearchSetting.ZincUser,
ZincPassword: global.SearchSetting.ZincPassword,
},
})
var (
myDao *dao.Dao
)
return svc
func Initialize(engine *gorm.DB, client *zinc.ZincClient) {
myDao = dao.New(engine, client)
}

@ -8,7 +8,7 @@ import (
"github.com/rocboss/paopao-ce/pkg/util"
)
func (svc *Service) GetParamSign(param map[string]interface{}, secretKey string) string {
func GetParamSign(param map[string]interface{}, secretKey string) string {
signRaw := ""
rawStrs := []string{}

@ -7,6 +7,7 @@ import (
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
"github.com/gofrs/uuid"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
@ -32,6 +33,7 @@ type AuthRequest struct {
Username string `json:"username" form:"username" binding:"required"`
Password string `json:"password" form:"password" binding:"required"`
}
type RegisterRequest struct {
Username string `json:"username" form:"username" binding:"required"`
Password string `json:"password" form:"password" binding:"required"`
@ -41,9 +43,11 @@ type ChangePasswordReq struct {
Password string `json:"password" form:"password" binding:"required"`
OldPassword string `json:"old_password" form:"old_password" binding:"required"`
}
type ChangeNicknameReq struct {
Nickname string `json:"nickname" form:"nickname" binding:"required"`
}
type ChangeAvatarReq struct {
Avatar string `json:"avatar" form:"avatar" binding:"required"`
}
@ -51,36 +55,36 @@ type ChangeAvatarReq struct {
const LOGIN_ERR_KEY = "PaoPaoUserLoginErr"
const MAX_LOGIN_ERR_TIMES = 10
// 用户认证
func (svc *Service) DoLogin(param *AuthRequest) (*model.User, error) {
user, err := svc.dao.GetUserByUsername(param.Username)
// DoLogin 用户认证
func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) {
user, err := myDao.GetUserByUsername(param.Username)
if err != nil {
return nil, errcode.UnauthorizedAuthNotExist
}
if user.Model != nil && user.ID > 0 {
if errTimes, err := global.Redis.Get(svc.ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil {
if errTimes, err := global.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil {
if convert.StrTo(errTimes).MustInt() >= MAX_LOGIN_ERR_TIMES {
return nil, errcode.TooManyLoginError
}
}
// 对比密码是否正确
if svc.ValidPassword(user.Password, param.Password, user.Salt) {
if ValidPassword(user.Password, param.Password, user.Salt) {
if user.Status == model.UserStatusClosed {
return nil, errcode.UserHasBeenBanned
}
// 清空登录计数
global.Redis.Del(svc.ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID))
global.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID))
return user, nil
}
// 登录错误计数
_, err = global.Redis.Incr(svc.ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result()
_, err = global.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result()
if err == nil {
global.Redis.Expire(svc.ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result()
global.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result()
}
return nil, errcode.UnauthorizedAuthFailed
@ -89,18 +93,18 @@ func (svc *Service) DoLogin(param *AuthRequest) (*model.User, error) {
return nil, errcode.UnauthorizedAuthNotExist
}
// 检查密码是否一致
func (svc *Service) ValidPassword(dbPassword, password, salt string) bool {
// ValidPassword 检查密码是否一致
func ValidPassword(dbPassword, password, salt string) bool {
return strings.Compare(dbPassword, util.EncodeMD5(util.EncodeMD5(password)+salt)) == 0
}
// 检测用户权限
func (svc *Service) CheckStatus(user *model.User) bool {
// CheckStatus 检测用户权限
func CheckStatus(user *model.User) bool {
return user.Status == model.UserStatusNormal
}
// 验证用户
func (svc *Service) ValidUsername(username string) error {
// ValidUsername 验证用户
func ValidUsername(username string) error {
// 检测用户是否合规
if utf8.RuneCountInString(username) < 3 || utf8.RuneCountInString(username) > 12 {
return errcode.UsernameLengthLimit
@ -111,7 +115,7 @@ func (svc *Service) ValidUsername(username string) error {
}
// 重复检查
user, _ := svc.dao.GetUserByUsername(username)
user, _ := myDao.GetUserByUsername(username)
if user.Model != nil && user.ID > 0 {
return errcode.UsernameHasExisted
@ -120,8 +124,8 @@ func (svc *Service) ValidUsername(username string) error {
return nil
}
// 密码检查
func (svc *Service) CheckPassword(password string) error {
// CheckPassword 密码检查
func CheckPassword(password string) error {
// 检测用户是否合规
if utf8.RuneCountInString(password) < 6 || utf8.RuneCountInString(password) > 16 {
return errcode.PasswordLengthLimit
@ -130,9 +134,9 @@ func (svc *Service) CheckPassword(password string) error {
return nil
}
// 验证手机验证码
func (svc *Service) CheckPhoneCaptcha(phone, captcha string) *errcode.Error {
c, err := svc.dao.GetLatestPhoneCaptcha(phone)
// CheckPhoneCaptcha 验证手机验证码
func CheckPhoneCaptcha(phone, captcha string) *errcode.Error {
c, err := myDao.GetLatestPhoneCaptcha(phone)
if err != nil {
return errcode.ErrorPhoneCaptcha
}
@ -150,14 +154,14 @@ func (svc *Service) CheckPhoneCaptcha(phone, captcha string) *errcode.Error {
}
// 更新检测次数
svc.dao.UsePhoneCaptcha(c)
myDao.UsePhoneCaptcha(c)
return nil
}
// 检测手机号是否存在
func (svc *Service) CheckPhoneExist(uid int64, phone string) bool {
u, err := svc.dao.GetUserByPhone(phone)
// CheckPhoneExist 检测手机号是否存在
func CheckPhoneExist(uid int64, phone string) bool {
u, err := myDao.GetUserByPhone(phone)
if err != nil {
return false
}
@ -173,28 +177,28 @@ func (svc *Service) CheckPhoneExist(uid int64, phone string) bool {
return true
}
// 密码加密&生成salt
func (svc *Service) EncryptPasswordAndSalt(password string) (string, string) {
// EncryptPasswordAndSalt 密码加密&生成salt
func EncryptPasswordAndSalt(password string) (string, string) {
salt := uuid.Must(uuid.NewV4()).String()[:8]
password = util.EncodeMD5(util.EncodeMD5(password) + salt)
return password, salt
}
// 用户注册
func (svc *Service) Register(username, password string) (*model.User, error) {
password, salt := svc.EncryptPasswordAndSalt(password)
// Register 用户注册
func Register(username, password string) (*model.User, error) {
password, salt := EncryptPasswordAndSalt(password)
user := &model.User{
Nickname: username,
Username: username,
Password: password,
Avatar: svc.GetRandomAvatar(),
Avatar: GetRandomAvatar(),
Salt: salt,
Status: model.UserStatusNormal,
}
user, err := svc.dao.CreateUser(user)
user, err := myDao.CreateUser(user)
if err != nil {
return nil, err
}
@ -202,9 +206,9 @@ func (svc *Service) Register(username, password string) (*model.User, error) {
return user, nil
}
// 获取用户信息
func (svc *Service) GetUserInfo(param *AuthRequest) (*model.User, error) {
user, err := svc.dao.GetUserByUsername(param.Username)
// GetUserInfo 获取用户信息
func GetUserInfo(param *AuthRequest) (*model.User, error) {
user, err := myDao.GetUserByUsername(param.Username)
if err != nil {
return nil, err
@ -217,8 +221,8 @@ func (svc *Service) GetUserInfo(param *AuthRequest) (*model.User, error) {
return nil, errcode.UnauthorizedAuthNotExist
}
func (svc *Service) GetUserByUsername(username string) (*model.User, error) {
user, err := svc.dao.GetUserByUsername(username)
func GetUserByUsername(username string) (*model.User, error) {
user, err := myDao.GetUserByUsername(username)
if err != nil {
return nil, err
@ -231,18 +235,18 @@ func (svc *Service) GetUserByUsername(username string) (*model.User, error) {
return nil, errcode.NoExistUsername
}
// 更新用户信息
func (svc *Service) UpdateUserInfo(user *model.User) error {
return svc.dao.UpdateUser(user)
// UpdateUserInfo 更新用户信息
func UpdateUserInfo(user *model.User) error {
return myDao.UpdateUser(user)
}
// 获取用户收藏列表
func (svc *Service) GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
collections, err := svc.dao.GetUserPostCollections(userID, offset, limit)
// GetUserCollections 获取用户收藏列表
func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
collections, err := myDao.GetUserPostCollections(userID, offset, limit)
if err != nil {
return nil, 0, err
}
totalRows, err := svc.dao.GetUserPostCollectionCount(userID)
totalRows, err := myDao.GetUserPostCollectionCount(userID)
if err != nil {
return nil, 0, err
}
@ -252,7 +256,7 @@ func (svc *Service) GetUserCollections(userID int64, offset, limit int) ([]*mode
}
// 获取Posts
posts, err := svc.dao.GetPosts(&model.ConditionsT{
posts, err := myDao.GetPosts(&model.ConditionsT{
"id IN ?": postIDs,
"ORDER": "id DESC",
}, 0, 0)
@ -260,7 +264,7 @@ func (svc *Service) GetUserCollections(userID int64, offset, limit int) ([]*mode
return nil, 0, err
}
postsFormated, err := svc.FormatPosts(posts)
postsFormated, err := FormatPosts(posts)
if err != nil {
return nil, 0, err
}
@ -268,13 +272,13 @@ func (svc *Service) GetUserCollections(userID int64, offset, limit int) ([]*mode
return postsFormated, totalRows, nil
}
// 获取用户点赞列表
func (svc *Service) GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
stars, err := svc.dao.GetUserPostStars(userID, offset, limit)
// GetUserStars 获取用户点赞列表
func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) {
stars, err := myDao.GetUserPostStars(userID, offset, limit)
if err != nil {
return nil, 0, err
}
totalRows, err := svc.dao.GetUserPostStarCount(userID)
totalRows, err := myDao.GetUserPostStarCount(userID)
if err != nil {
return nil, 0, err
}
@ -284,7 +288,7 @@ func (svc *Service) GetUserStars(userID int64, offset, limit int) ([]*model.Post
}
// 获取Posts
posts, err := svc.dao.GetPosts(&model.ConditionsT{
posts, err := myDao.GetPosts(&model.ConditionsT{
"id IN ?": postIDs,
"ORDER": "id DESC",
}, 0, 0)
@ -292,7 +296,7 @@ func (svc *Service) GetUserStars(userID int64, offset, limit int) ([]*model.Post
return nil, 0, err
}
postsFormated, err := svc.FormatPosts(posts)
postsFormated, err := FormatPosts(posts)
if err != nil {
return nil, 0, err
}
@ -300,13 +304,13 @@ func (svc *Service) GetUserStars(userID int64, offset, limit int) ([]*model.Post
return postsFormated, totalRows, nil
}
// 获取用户账单列表
func (svc *Service) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, int64, error) {
bills, err := svc.dao.GetUserWalletBills(userID, offset, limit)
// GetUserWalletBills 获取用户账单列表
func GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, int64, error) {
bills, err := myDao.GetUserWalletBills(userID, offset, limit)
if err != nil {
return nil, 0, err
}
totalRows, err := svc.dao.GetUserWalletBillCount(userID)
totalRows, err := myDao.GetUserWalletBillCount(userID)
if err != nil {
return nil, 0, err
}
@ -314,28 +318,28 @@ func (svc *Service) GetUserWalletBills(userID int64, offset, limit int) ([]*mode
return bills, totalRows, nil
}
// 发送短信验证码
func (svc *Service) SendPhoneCaptcha(phone string) error {
// SendPhoneCaptcha 发送短信验证码
func SendPhoneCaptcha(ctx *gin.Context, phone string) error {
err := svc.dao.SendPhoneCaptcha(phone)
err := myDao.SendPhoneCaptcha(phone)
if err != nil {
return err
}
// 写入计数缓存
global.Redis.Incr(svc.ctx, "PaoPaoSmsCaptcha:"+phone).Result()
global.Redis.Incr(ctx, "PaoPaoSmsCaptcha:"+phone).Result()
currentTime := time.Now()
endTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 23, 59, 59, 0, currentTime.Location())
global.Redis.Expire(svc.ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime))
global.Redis.Expire(ctx, "PaoPaoSmsCaptcha:"+phone, endTime.Sub(currentTime))
return nil
}
// 根据关键词获取用户推荐
func (svc *Service) GetSuggestUsers(keyword string) ([]string, error) {
users, err := svc.dao.GetUsersByKeyword(keyword)
// GetSuggestUsers 根据关键词获取用户推荐
func GetSuggestUsers(keyword string) ([]string, error) {
users, err := myDao.GetUsersByKeyword(keyword)
if err != nil {
return nil, err
}
@ -348,9 +352,9 @@ func (svc *Service) GetSuggestUsers(keyword string) ([]string, error) {
return usernames, nil
}
// 根据关键词获取标签推荐
func (svc *Service) GetSuggestTags(keyword string) ([]string, error) {
tags, err := svc.dao.GetTagsByKeyword(keyword)
// GetSuggestTags 根据关键词获取标签推荐
func GetSuggestTags(keyword string) ([]string, error) {
tags, err := myDao.GetTagsByKeyword(keyword)
if err != nil {
return nil, err
}

@ -3,6 +3,7 @@ package service
import (
"time"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/global"
"github.com/rocboss/paopao-ce/internal/model"
"github.com/rocboss/paopao-ce/pkg/errcode"
@ -12,17 +13,17 @@ type RechargeReq struct {
Amount int64 `json:"amount" form:"amount" binding:"required"`
}
func (svc *Service) GetRechargeByID(id int64) (*model.WalletRecharge, error) {
return svc.dao.GetRechargeByID(id)
func GetRechargeByID(id int64) (*model.WalletRecharge, error) {
return myDao.GetRechargeByID(id)
}
func (svc *Service) CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) {
return svc.dao.CreateRecharge(userID, amount)
func CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) {
return myDao.CreateRecharge(userID, amount)
}
func (svc *Service) FinishRecharge(id int64, tradeNo string) error {
if ok, _ := global.Redis.SetNX(svc.ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok {
recharge, err := svc.dao.GetRechargeByID(id)
func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error {
if ok, _ := global.Redis.SetNX(ctx, "PaoPaoRecharge:"+tradeNo, 1, time.Second*5).Result(); ok {
recharge, err := myDao.GetRechargeByID(id)
if err != nil {
return err
}
@ -30,8 +31,8 @@ func (svc *Service) FinishRecharge(id int64, tradeNo string) error {
if recharge.TradeStatus != "TRADE_SUCCESS" {
// 标记为已付款
err := svc.dao.HandleRechargeSuccess(recharge, tradeNo)
defer global.Redis.Del(svc.ctx, "PaoPaoRecharge:"+tradeNo)
err := myDao.HandleRechargeSuccess(recharge, tradeNo)
defer global.Redis.Del(ctx, "PaoPaoRecharge:"+tradeNo)
if err != nil {
return err
@ -43,11 +44,11 @@ func (svc *Service) FinishRecharge(id int64, tradeNo string) error {
return nil
}
func (svc *Service) BuyPostAttachment(post *model.Post, user *model.User) error {
func BuyPostAttachment(post *model.Post, user *model.User) error {
if user.Balance < post.AttachmentPrice {
return errcode.InsuffientDownloadMoney
}
// 执行购买
return svc.dao.HandlePostAttachmentBought(post, user)
return myDao.HandlePostAttachmentBought(post, user)
}

@ -8,6 +8,7 @@ import (
"time"
"github.com/go-resty/resty/v2"
"github.com/rocboss/paopao-ce/pkg/setting"
)
type ZincClient struct {
@ -49,14 +50,17 @@ type QueryResultT struct {
TimedOut bool `json:"timed_out"`
Hits *HitsResultT `json:"hits"`
}
type HitsResultT struct {
Total *HitsResultTotalT `json:"total"`
MaxScore float64 `json:"max_score"`
Hits []*HitItem `json:"hits"`
}
type HitsResultTotalT struct {
Value int64 `json:"value"`
}
type HitItem struct {
Index string `json:"_index"`
Type string `json:"_type"`
@ -66,6 +70,17 @@ type HitItem struct {
Source interface{} `json:"_source"`
}
// NewClient 获取ZincClient新实例
func NewClient(conf *setting.SearchSettingS) *ZincClient {
return &ZincClient{
ZincClientConfig: &ZincClientConfig{
ZincHost: conf.ZincHost,
ZincUser: conf.ZincUser,
ZincPassword: conf.ZincPassword,
},
}
}
// 创建索引
func (c *ZincClient) CreateIndex(name string, p *ZincIndexProperty) bool {
data := &ZincIndex{

Loading…
Cancel
Save