diff --git a/Makefile b/Makefile index 4d0b94a2..700e2d29 100644 --- a/Makefile +++ b/Makefile @@ -68,6 +68,11 @@ windows-x64: @echo Build paopao-ce [windows-x64] CGO_ENABLED=$(CGO_ENABLED) @CGO_ENABLED=$(CGO_ENABLED) GOOS=windows GOARCH=amd64 go build -trimpath -tags '$(TAGS)' -ldflags '$(LDFLAGS)' -o $(RELEASE_WINDOWS_AMD64)/$(basename $(TARGET)).exe +.PHONY: generate +generate: + @go generate internal/mirc/main.go + @go fmt ./internal/mirc/... + clean: @go clean @find ./release -type f -exec rm -r {} + diff --git a/config.yaml.sample b/config.yaml.sample index d776769b..1126bcec 100644 --- a/config.yaml.sample +++ b/config.yaml.sample @@ -1,4 +1,5 @@ App: # APP基础设置项 + RunMode: debug AttachmentIncomeRate: 0.8 MaxCommentCount: 10 DefaultContextTimeout: 60 @@ -17,8 +18,19 @@ Features: Slim: ["Base", "Sqlite3", "LocalOSS", "LoggerFile", "OSS:TempDir"] Base: ["Redis", "PhoneBind"] Docs: ["Docs:OpenAPI"] + Deprecated: ["Deprecated:OldWeb"] Option: ["SimpleCacheIndex"] Sms: "SmsJuhe" +WebServer: # Web服务 + HttpIp: 0.0.0.0 + HttpPort: 8010 + ReadTimeout: 60 + WriteTimeout: 60 +DocsServer: # 开发文档服务 + HttpIp: 0.0.0.0 + HttpPort: 8011 + ReadTimeout: 60 + WriteTimeout: 60 SmsJuhe: Gateway: https://v.juhe.cn/sms/send Key: diff --git a/docs/openapi/embed.go b/docs/openapi/embed.go index 8500ca3c..e72721fb 100644 --- a/docs/openapi/embed.go +++ b/docs/openapi/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build docs // +build docs diff --git a/go.mod b/go.mod index 8f4c9435..83348535 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.18 require ( github.com/Masterminds/semver/v3 v3.1.1 github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868 + github.com/alimy/mir/v3 v3.0.0-alpha.3 github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible github.com/allegro/bigcache/v3 v3.0.2 github.com/bytedance/sonic v1.5.0 diff --git a/go.sum b/go.sum index 9221a97a..84ae8631 100644 --- a/go.sum +++ b/go.sum @@ -142,6 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk= +github.com/alimy/mir/v3 v3.0.0-alpha.3 h1:/GyBC0G041NIP3W62im8DtAwxRPSfSaivSQK6MV9fFc= +github.com/alimy/mir/v3 v3.0.0-alpha.3/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM= github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= diff --git a/internal/conf/conf.go b/internal/conf/conf.go index 97512264..1cffa824 100644 --- a/internal/conf/conf.go +++ b/internal/conf/conf.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( @@ -20,6 +24,8 @@ var ( PostgresSetting *PostgresSettingS Sqlite3Setting *Sqlite3SettingS ServerSetting *ServerSettingS + WebServerSetting *ServerSettingS + DocsServerSetting *ServerSettingS AppSetting *AppSettingS CacheIndexSetting *CacheIndexSettingS SimpleCacheIndexSetting *SimpleCacheIndexSettingS @@ -56,6 +62,8 @@ func setupSetting(suite []string, noDefault bool) error { objects := map[string]any{ "App": &AppSetting, "Server": &ServerSetting, + "WebServer": &WebServerSetting, + "DocsServer": &DocsServerSetting, "CacheIndex": &CacheIndexSetting, "SimpleCacheIndex": &SimpleCacheIndexSetting, "BigCacheIndex": &BigCacheIndexSetting, @@ -134,3 +142,10 @@ func GetOssDomain() string { } return uri + AliOSSSetting.Domain + "/" } + +func RunMode() string { + if !cfg.If("Deprecated:OldWeb") { + return ServerSetting.RunMode + } + return AppSetting.RunMode +} diff --git a/internal/conf/db.go b/internal/conf/db.go index ef4f7c92..7f859152 100644 --- a/internal/conf/db.go +++ b/internal/conf/db.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/db_cgo.go b/internal/conf/db_cgo.go index 3ec8a218..218512a5 100644 --- a/internal/conf/db_cgo.go +++ b/internal/conf/db_cgo.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build cgo // +build cgo diff --git a/internal/conf/db_nocgo.go b/internal/conf/db_nocgo.go index 37937484..977a6695 100644 --- a/internal/conf/db_nocgo.go +++ b/internal/conf/db_nocgo.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !cgo // +build !cgo diff --git a/internal/conf/logger.go b/internal/conf/logger.go index c65612dc..b514b375 100644 --- a/internal/conf/logger.go +++ b/internal/conf/logger.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/logger_meili.go b/internal/conf/logger_meili.go index 756cc41f..2d3d439d 100644 --- a/internal/conf/logger_meili.go +++ b/internal/conf/logger_meili.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/logger_zinc.go b/internal/conf/logger_zinc.go index 211270c0..4f804cf8 100644 --- a/internal/conf/logger_zinc.go +++ b/internal/conf/logger_zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( diff --git a/internal/conf/settting.go b/internal/conf/settting.go index 116fdf95..e5841c51 100644 --- a/internal/conf/settting.go +++ b/internal/conf/settting.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package conf import ( @@ -50,6 +54,7 @@ type ServerSettingS struct { } type AppSettingS struct { + RunMode string MaxCommentCount int64 AttachmentIncomeRate float64 DefaultContextTimeout time.Duration diff --git a/internal/core/authority.go b/internal/core/authority.go index c016c840..05e3742a 100644 --- a/internal/core/authority.go +++ b/internal/core/authority.go @@ -1,7 +1,10 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/types" ) @@ -33,23 +36,17 @@ const ( ActCreateActivationCode ) -type act uint8 - -type FriendFilter map[int64]types.Empty -type FriendSet map[string]types.Empty +type ( + act uint8 -type Action struct { - Act act - UserId int64 -} + FriendFilter map[int64]types.Empty + FriendSet map[string]types.Empty -// AuthorizationManageService 授权管理服务 -type AuthorizationManageService interface { - IsAllow(user *model.User, action *Action) bool - BeFriendFilter(userId int64) FriendFilter - BeFriendIds(userId int64) ([]int64, error) - MyFriendSet(userId int64) FriendSet -} + Action struct { + Act act + UserId int64 + } +) func (f FriendFilter) IsFriend(userId int64) bool { _, yeah := f[userId] @@ -57,7 +54,7 @@ func (f FriendFilter) IsFriend(userId int64) bool { } // IsAllow default true if user is admin -func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation bool) bool { +func (a act) IsAllow(user *User, userId int64, isFriend bool, isActivation bool) bool { if user.IsAdmin { return true } @@ -116,3 +113,11 @@ func (a act) IsAllow(user *model.User, userId int64, isFriend bool, isActivation return false } + +// AuthorizationManageService 授权管理服务 +type AuthorizationManageService interface { + IsAllow(user *User, action *Action) bool + BeFriendFilter(userId int64) FriendFilter + BeFriendIds(userId int64) ([]int64, error) + MyFriendSet(userId int64) FriendSet +} diff --git a/internal/core/cache.go b/internal/core/cache.go index e4cf4cd9..d8b8cd10 100644 --- a/internal/core/cache.go +++ b/internal/core/cache.go @@ -1,6 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core -import "github.com/rocboss/paopao-ce/internal/model" +import ( + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) const ( IdxActNop IdxAct = iota + 1 @@ -15,7 +21,7 @@ type IdxAct uint8 type IndexAction struct { Act IdxAct - Post *model.Post + Post *dbr.Post } func (a IdxAct) String() string { @@ -37,7 +43,7 @@ func (a IdxAct) String() string { } } -func NewIndexAction(act IdxAct, post *model.Post) *IndexAction { +func NewIndexAction(act IdxAct, post *dbr.Post) *IndexAction { return &IndexAction{ Act: act, Post: post, @@ -48,5 +54,5 @@ func NewIndexAction(act IdxAct, post *model.Post) *IndexAction { type CacheIndexService interface { IndexPostsService - SendAction(act IdxAct, post *model.Post) + SendAction(act IdxAct, post *dbr.Post) } diff --git a/internal/core/comments.go b/internal/core/comments.go index 9be29ed3..c5501b4b 100644 --- a/internal/core/comments.go +++ b/internal/core/comments.go @@ -1,24 +1,36 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Comment = dbr.Comment + CommentFormated = dbr.CommentFormated + CommentReply = dbr.CommentReply + CommentContent = dbr.CommentContent + CommentReplyFormated = dbr.CommentReplyFormated ) // CommentService 评论检索服务 type CommentService interface { - GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error) - GetCommentByID(id int64) (*model.Comment, error) - GetCommentCount(conditions *model.ConditionsT) (int64, error) - GetCommentReplyByID(id int64) (*model.CommentReply, error) - GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error) - GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error) + GetComments(conditions *ConditionsT, offset, limit int) ([]*Comment, error) + GetCommentByID(id int64) (*Comment, error) + GetCommentCount(conditions *ConditionsT) (int64, error) + GetCommentReplyByID(id int64) (*CommentReply, error) + GetCommentContentsByIDs(ids []int64) ([]*CommentContent, error) + GetCommentRepliesByID(ids []int64) ([]*CommentReplyFormated, error) } // CommentManageService 评论管理服务 type CommentManageService interface { - DeleteComment(comment *model.Comment) error - CreateComment(comment *model.Comment) (*model.Comment, error) - CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error) - DeleteCommentReply(reply *model.CommentReply) error - CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error) + DeleteComment(comment *Comment) error + CreateComment(comment *Comment) (*Comment, error) + CreateCommentReply(reply *CommentReply) (*CommentReply, error) + DeleteCommentReply(reply *CommentReply) error + CreateCommentContent(content *CommentContent) (*CommentContent, error) } diff --git a/internal/core/core.go b/internal/core/core.go index f0c158b1..9a8eb26f 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core // DataService 数据服务集成 diff --git a/internal/core/messages.go b/internal/core/messages.go index aa08a1f8..57816480 100644 --- a/internal/core/messages.go +++ b/internal/core/messages.go @@ -1,15 +1,36 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + MsgTypePost = dbr.MsgTypePost + MsgtypeComment = dbr.MsgtypeComment + MsgTypeReply = dbr.MsgTypeReply + MsgTypeWhisper = dbr.MsgTypeWhisper + MsgTypeRequestingFriend = dbr.MsgTypeRequestingFriend + MsgTypeSystem = dbr.MsgTypeSystem + + MsgStatusUnread = dbr.MsgStatusUnread + MsgStatusReaded = dbr.MsgStatusReaded +) + +type ( + Message = dbr.Message + MessageFormated = dbr.MessageFormated ) // MessageService 消息服务 type MessageService interface { - CreateMessage(msg *model.Message) (*model.Message, error) + CreateMessage(msg *Message) (*Message, error) GetUnreadCount(userID int64) (int64, error) - GetMessageByID(id int64) (*model.Message, error) - ReadMessage(message *model.Message) error - GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error) - GetMessageCount(conditions *model.ConditionsT) (int64, error) + GetMessageByID(id int64) (*Message, error) + ReadMessage(message *Message) error + GetMessages(conditions *ConditionsT, offset, limit int) ([]*MessageFormated, error) + GetMessageCount(conditions *ConditionsT) (int64, error) } diff --git a/internal/core/search.go b/internal/core/search.go index 3ac90288..74d6e029 100644 --- a/internal/core/search.go +++ b/internal/core/search.go @@ -1,7 +1,11 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" ) const ( @@ -9,28 +13,39 @@ const ( SearchTypeTag SearchType = "tag" ) -type SearchType string +const ( + PostVisitPublic = dbr.PostVisitPublic + PostVisitPrivate = dbr.PostVisitPrivate + PostVisitFriend = dbr.PostVisitFriend + PostVisitInvalid = dbr.PostVisitInvalid +) -type QueryReq struct { - Query string - Visibility []model.PostVisibleT - Type SearchType -} +type ( + PostVisibleT = dbr.PostVisibleT -type QueryResp struct { - Items []*model.PostFormated - Total int64 -} + SearchType string -type TsDocItem struct { - Post *model.Post - Content string -} + QueryReq struct { + Query string + Visibility []PostVisibleT + Type SearchType + } + + QueryResp struct { + Items []*PostFormated + Total int64 + } + + TsDocItem struct { + Post *Post + Content string + } +) // TweetSearchService tweet search service interface type TweetSearchService interface { IndexName() string AddDocuments(data []TsDocItem, primaryKey ...string) (bool, error) DeleteDocuments(identifiers []string) error - Search(user *model.User, q *QueryReq, offset, limit int) (*QueryResp, error) + Search(user *User, q *QueryReq, offset, limit int) (*QueryResp, error) } diff --git a/internal/core/security.go b/internal/core/security.go index 63a7ac21..81a428af 100644 --- a/internal/core/security.go +++ b/internal/core/security.go @@ -1,13 +1,21 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Captcha = dbr.Captcha ) // SecurityService 安全相关服务 type SecurityService interface { - GetLatestPhoneCaptcha(phone string) (*model.Captcha, error) - UsePhoneCaptcha(captcha *model.Captcha) error + GetLatestPhoneCaptcha(phone string) (*Captcha, error) + UsePhoneCaptcha(captcha *Captcha) error SendPhoneCaptcha(phone string) error } diff --git a/internal/core/storage.go b/internal/core/storage.go index 2a241bca..310edf29 100644 --- a/internal/core/storage.go +++ b/internal/core/storage.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( diff --git a/internal/core/topics.go b/internal/core/topics.go index a894f9b2..138cc151 100644 --- a/internal/core/topics.go +++ b/internal/core/topics.go @@ -1,13 +1,22 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + Tag = dbr.Tag + TagFormated = dbr.TagFormated ) // TopicService 话题服务 type TopicService interface { - CreateTag(tag *model.Tag) (*model.Tag, error) - DeleteTag(tag *model.Tag) error - GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error) - GetTagsByKeyword(keyword string) ([]*model.Tag, error) + CreateTag(tag *Tag) (*Tag, error) + DeleteTag(tag *Tag) error + GetTags(conditions *ConditionsT, offset, limit int) ([]*Tag, error) + GetTagsByKeyword(keyword string) ([]*Tag, error) } diff --git a/internal/core/tweets.go b/internal/core/tweets.go index 1b454c6d..682cbd65 100644 --- a/internal/core/tweets.go +++ b/internal/core/tweets.go @@ -1,49 +1,83 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + AttachmentTypeImage = dbr.AttachmentTypeImage + AttachmentTypeVideo = dbr.AttachmentTypeVideo + AttachmentTypeOther = dbr.AttachmentTypeOther + + // 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 + ContentTypeTitle = dbr.ContentTypeTitle + ContentTypeText = dbr.ContentTypeText + ContentTypeImage = dbr.ContentTypeImage + ContentTypeVideo = dbr.ContentTypeVideo + ContentTypeAudio = dbr.ContentTypeAudio + ContentTypeLink = dbr.ContentTypeLink + ContentTypeAttachment = dbr.ContentTypeAttachment + ContentTypeChargeAttachment = dbr.ContentTypeChargeAttachment +) + +type ( + PostStar = dbr.PostStar + PostCollection = dbr.PostCollection + PostAttachmentBill = dbr.PostAttachmentBill + PostContent = dbr.PostContent + Attachment = dbr.Attachment + AttachmentType = dbr.AttachmentType + PostContentT = dbr.PostContentT + + IndexTweetList struct { + Tweets []*PostFormated + Total int64 + } ) // TweetService 推文检索服务 type TweetService interface { - GetPostByID(id int64) (*model.Post, error) - GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error) - GetPostCount(conditions *model.ConditionsT) (int64, error) - GetUserPostStar(postID, userID int64) (*model.PostStar, error) - GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error) + GetPostByID(id int64) (*Post, error) + GetPosts(conditions *ConditionsT, offset, limit int) ([]*Post, error) + GetPostCount(conditions *ConditionsT) (int64, error) + GetUserPostStar(postID, userID int64) (*PostStar, error) + GetUserPostStars(userID int64, offset, limit int) ([]*PostStar, error) GetUserPostStarCount(userID int64) (int64, error) - GetUserPostCollection(postID, userID int64) (*model.PostCollection, error) - GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error) + GetUserPostCollection(postID, userID int64) (*PostCollection, error) + GetUserPostCollections(userID int64, offset, limit int) ([]*PostCollection, error) GetUserPostCollectionCount(userID int64) (int64, error) - GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error) - GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error) - GetPostContentByID(id int64) (*model.PostContent, error) + GetPostAttatchmentBill(postID, userID int64) (*PostAttachmentBill, error) + GetPostContentsByIDs(ids []int64) ([]*PostContent, error) + GetPostContentByID(id int64) (*PostContent, error) } // TweetManageService 推文管理服务,包括创建/删除/更新推文 type TweetManageService interface { - CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) - CreatePost(post *model.Post) (*model.Post, error) - DeletePost(post *model.Post) ([]string, error) - LockPost(post *model.Post) error - StickPost(post *model.Post) error - VisiblePost(post *model.Post, visibility model.PostVisibleT) error - UpdatePost(post *model.Post) error - CreatePostStar(postID, userID int64) (*model.PostStar, error) - DeletePostStar(p *model.PostStar) error - CreatePostCollection(postID, userID int64) (*model.PostCollection, error) - DeletePostCollection(p *model.PostCollection) error - CreatePostContent(content *model.PostContent) (*model.PostContent, error) + CreateAttachment(attachment *Attachment) (*Attachment, error) + CreatePost(post *Post) (*Post, error) + DeletePost(post *Post) ([]string, error) + LockPost(post *Post) error + StickPost(post *Post) error + VisiblePost(post *Post, visibility PostVisibleT) error + UpdatePost(post *Post) error + CreatePostStar(postID, userID int64) (*PostStar, error) + DeletePostStar(p *PostStar) error + CreatePostCollection(postID, userID int64) (*PostCollection, error) + DeletePostCollection(p *PostCollection) error + CreatePostContent(content *PostContent) (*PostContent, error) } // TweetHelpService 推文辅助服务 type TweetHelpService interface { - RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error) - MergePosts(posts []*model.Post) ([]*model.PostFormated, error) + RevampPosts(posts []*PostFormated) ([]*PostFormated, error) + MergePosts(posts []*Post) ([]*PostFormated, error) } // IndexPostsService 广场首页推文列表服务 type IndexPostsService interface { - IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) + IndexPosts(user *User, offset int, limit int) (*IndexTweetList, error) } diff --git a/internal/core/types.go b/internal/core/types.go new file mode 100644 index 00000000..6ca95893 --- /dev/null +++ b/internal/core/types.go @@ -0,0 +1,24 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package core + +import ( + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +const ( + UserStatusNormal = dbr.UserStatusNormal + UserStatusClosed = dbr.UserStatusClosed +) + +type ( + User = dbr.User + Post = dbr.Post + ConditionsT = dbr.ConditionsT + PostFormated = dbr.PostFormated + UserFormated = dbr.UserFormated + PostContentFormated = dbr.PostContentFormated + Model = dbr.Model +) diff --git a/internal/core/user.go b/internal/core/user.go index cf0ebaa8..ed132dd3 100644 --- a/internal/core/user.go +++ b/internal/core/user.go @@ -1,19 +1,33 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core -import ( - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" +type ( + ContactItem struct { + UserId int64 `json:"user_id"` + UserName string `json:"username"` + Nickname string `json:"nickname"` + Avatar string `json:"avatar"` + Phone string `json:"phone"` + } + + ContactList struct { + Contacts []ContactItem `json:"contacts"` + Total int64 `json:"total"` + } ) // UserManageService 用户管理服务 type UserManageService interface { - GetUserByID(id int64) (*model.User, error) - GetUserByUsername(username string) (*model.User, error) - GetUserByPhone(phone string) (*model.User, error) - GetUsersByIDs(ids []int64) ([]*model.User, error) - GetUsersByKeyword(keyword string) ([]*model.User, error) - CreateUser(user *model.User) (*model.User, error) - UpdateUser(user *model.User) error + GetUserByID(id int64) (*User, error) + GetUserByUsername(username string) (*User, error) + GetUserByPhone(phone string) (*User, error) + GetUsersByIDs(ids []int64) ([]*User, error) + GetUsersByKeyword(keyword string) ([]*User, error) + CreateUser(user *User) (*User, error) + UpdateUser(user *User) error } // ContactManageService 联系人管理服务 @@ -22,6 +36,6 @@ type ContactManageService interface { AddFriend(userId int64, friendId int64) error RejectFriend(userId int64, friendId int64) error DeleteFriend(userId int64, friendId int64) error - GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error) + GetContacts(userId int64, offset int, limit int) (*ContactList, error) IsFriend(userID int64, friendID int64) bool } diff --git a/internal/core/version.go b/internal/core/version.go index e603c0a5..07376c39 100644 --- a/internal/core/version.go +++ b/internal/core/version.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( diff --git a/internal/core/wallet.go b/internal/core/wallet.go index 5b3a3391..c4792d3b 100644 --- a/internal/core/wallet.go +++ b/internal/core/wallet.go @@ -1,15 +1,24 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package core import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" +) + +type ( + WalletStatement = dbr.WalletStatement + WalletRecharge = dbr.WalletRecharge ) // WalletService wallet service interface type WalletService interface { - GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) + GetUserWalletBills(userID int64, offset, limit int) ([]*WalletStatement, error) GetUserWalletBillCount(userID int64) (int64, error) - GetRechargeByID(id int64) (*model.WalletRecharge, error) - CreateRecharge(userId, amount int64) (*model.WalletRecharge, error) - HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error - HandlePostAttachmentBought(post *model.Post, user *model.User) error + GetRechargeByID(id int64) (*WalletRecharge, error) + CreateRecharge(userId, amount int64) (*WalletRecharge, error) + HandleRechargeSuccess(recharge *WalletRecharge, tradeNo string) error + HandlePostAttachmentBought(post *Post, user *User) error } diff --git a/internal/dao/cache/bigcache.go b/internal/dao/cache/bigcache.go index 4fce26de..8ec83c38 100644 --- a/internal/dao/cache/bigcache.go +++ b/internal/dao/cache/bigcache.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( @@ -11,8 +15,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/allegro/bigcache/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/rocboss/paopao-ce/pkg/types" "github.com/sirupsen/logrus" ) @@ -24,7 +26,7 @@ var ( type postsEntry struct { key string - tweets *rest.IndexTweetsResp + tweets *core.IndexTweetList } type bigCacheIndexServant struct { @@ -38,7 +40,7 @@ type bigCacheIndexServant struct { preventDuration time.Duration } -func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func (s *bigCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { key := s.keyFrom(user, offset, limit) posts, err := s.getPosts(key) if err == nil { @@ -54,7 +56,7 @@ func (s *bigCacheIndexServant) IndexPosts(user *model.User, offset int, limit in return posts, nil } -func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, error) { +func (s *bigCacheIndexServant) getPosts(key string) (*core.IndexTweetList, error) { data, err := s.cache.Get(key) if err != nil { logrus.Debugf("bigCacheIndexServant.getPosts get posts by key: %s from cache err: %v", key, err) @@ -62,7 +64,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro } buf := bytes.NewBuffer(data) dec := gob.NewDecoder(buf) - var resp rest.IndexTweetsResp + var resp core.IndexTweetList if err := dec.Decode(&resp); err != nil { logrus.Debugf("bigCacheIndexServant.getPosts get posts from cache in decode err: %v", err) return nil, err @@ -70,7 +72,7 @@ func (s *bigCacheIndexServant) getPosts(key string) (*rest.IndexTweetsResp, erro return &resp, nil } -func (s *bigCacheIndexServant) cachePosts(key string, tweets *rest.IndexTweetsResp) { +func (s *bigCacheIndexServant) cachePosts(key string, tweets *core.IndexTweetList) { entry := &postsEntry{key: key, tweets: tweets} select { case s.cachePostsCh <- entry: @@ -96,7 +98,7 @@ func (s *bigCacheIndexServant) setPosts(entry *postsEntry) { logrus.Debugf("bigCacheIndexServant.setPosts setPosts set cache by key: %s", entry.key) } -func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int) string { +func (s *bigCacheIndexServant) keyFrom(user *core.User, offset int, limit int) string { var userId int64 = -1 if user != nil { userId = user.ID @@ -104,7 +106,7 @@ func (s *bigCacheIndexServant) keyFrom(user *model.User, offset int, limit int) return fmt.Sprintf("index:%d:%d:%d", userId, offset, limit) } -func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *model.Post) { +func (s *bigCacheIndexServant) SendAction(act core.IdxAct, post *core.Post) { action := core.NewIndexAction(act, post) select { case s.indexActionCh <- action: @@ -134,7 +136,7 @@ func (s *bigCacheIndexServant) handleIndexAction(action *core.IndexAction) { // 创建/删除 私密推文特殊处理 switch act { case core.IdxActCreatePost, core.IdxActDeletePost: - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { s.deleteCacheByUserId(post.UserID, true) return } diff --git a/internal/dao/cache/cache.go b/internal/dao/cache/cache.go index 1b12ad88..773c9a2f 100644 --- a/internal/dao/cache/cache.go +++ b/internal/dao/cache/cache.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( diff --git a/internal/dao/cache/none.go b/internal/dao/cache/none.go index 79705280..ce6e1caf 100644 --- a/internal/dao/cache/none.go +++ b/internal/dao/cache/none.go @@ -1,10 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" ) var ( @@ -16,11 +18,11 @@ type noneCacheIndexServant struct { ips core.IndexPostsService } -func (s *noneCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func (s *noneCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { return s.ips.IndexPosts(user, offset, limit) } -func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *model.Post) { +func (s *noneCacheIndexServant) SendAction(_act core.IdxAct, _post *core.Post) { // empty } diff --git a/internal/dao/cache/simple.go b/internal/dao/cache/simple.go index afdea1be..ba674d1b 100644 --- a/internal/dao/cache/simple.go +++ b/internal/dao/cache/simple.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cache import ( @@ -6,8 +10,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/sirupsen/logrus" ) @@ -20,21 +22,21 @@ type simpleCacheIndexServant struct { ips core.IndexPostsService indexActionCh chan core.IdxAct - indexPosts *rest.IndexTweetsResp + indexPosts *core.IndexTweetList atomicIndex atomic.Value maxIndexSize int checkTick *time.Ticker expireIndexTick *time.Ticker } -func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - cacheResp := s.atomicIndex.Load().(*rest.IndexTweetsResp) +func (s *simpleCacheIndexServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + cacheResp := s.atomicIndex.Load().(*core.IndexTweetList) end := offset + limit if cacheResp != nil { size := len(cacheResp.Tweets) logrus.Debugf("simpleCacheIndexServant.IndexPosts get index posts from cache posts: %d offset:%d limit:%d start:%d, end:%d", size, offset, limit, offset, end) if size >= end { - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: cacheResp.Tweets[offset:end], Total: cacheResp.Total, }, nil @@ -45,7 +47,7 @@ func (s *simpleCacheIndexServant) IndexPosts(user *model.User, offset int, limit return s.ips.IndexPosts(user, offset, limit) } -func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *model.Post) { +func (s *simpleCacheIndexServant) SendAction(act core.IdxAct, _post *core.Post) { select { case s.indexActionCh <- act: logrus.Debugf("simpleCacheIndexServant.SendAction send indexAction by chan: %s", act) diff --git a/internal/dao/dao.go b/internal/dao/dao.go index 6f4a776a..e4b2ea6a 100644 --- a/internal/dao/dao.go +++ b/internal/dao/dao.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package dao import ( diff --git a/internal/dao/jinzhu/authority.go b/internal/dao/jinzhu/authority.go index c0f59556..5932fa24 100644 --- a/internal/dao/jinzhu/authority.go +++ b/internal/dao/jinzhu/authority.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/rocboss/paopao-ce/pkg/types" "gorm.io/gorm" ) @@ -21,7 +25,7 @@ func newAuthorizationManageService(db *gorm.DB) core.AuthorizationManageService } } -func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Action) bool { +func (s *authorizationManageServant) IsAllow(user *core.User, action *core.Action) bool { // user is activation if had bind phone isActivation := (len(user.Phone) != 0) isFriend := s.isFriend(user.ID, action.UserId) @@ -30,7 +34,7 @@ func (s *authorizationManageServant) IsAllow(user *model.User, action *core.Acti } func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet { - ids, err := (&model.Contact{UserId: userId}).MyFriendIds(s.db) + ids, err := (&dbr.Contact{UserId: userId}).MyFriendIds(s.db) if err != nil { return core.FriendSet{} } @@ -43,7 +47,7 @@ func (s *authorizationManageServant) MyFriendSet(userId int64) core.FriendSet { } func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFilter { - ids, err := (&model.Contact{FriendId: userId}).BeFriendIds(s.db) + ids, err := (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db) if err != nil { return core.FriendFilter{} } @@ -56,12 +60,12 @@ func (s *authorizationManageServant) BeFriendFilter(userId int64) core.FriendFil } func (s *authorizationManageServant) BeFriendIds(userId int64) ([]int64, error) { - return (&model.Contact{FriendId: userId}).BeFriendIds(s.db) + return (&dbr.Contact{FriendId: userId}).BeFriendIds(s.db) } func (s *authorizationManageServant) isFriend(userId int64, friendId int64) bool { - contact, err := (&model.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db) - if err == nil || contact.Status == model.ContactStatusAgree { + contact, err := (&dbr.Contact{UserId: friendId, FriendId: userId}).GetByUserFriend(s.db) + if err == nil || contact.Status == dbr.ContactStatusAgree { return true } return false diff --git a/internal/dao/jinzhu/comments.go b/internal/dao/jinzhu/comments.go index c15e74f3..1af9e5ce 100644 --- a/internal/dao/jinzhu/comments.go +++ b/internal/dao/jinzhu/comments.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -31,42 +35,42 @@ func newCommentManageService(db *gorm.DB) core.CommentManageService { } } -func (s *commentServant) GetComments(conditions *model.ConditionsT, offset, limit int) ([]*model.Comment, error) { - return (&model.Comment{}).List(s.db, conditions, offset, limit) +func (s *commentServant) GetComments(conditions *core.ConditionsT, offset, limit int) ([]*core.Comment, error) { + return (&dbr.Comment{}).List(s.db, conditions, offset, limit) } -func (s *commentServant) GetCommentByID(id int64) (*model.Comment, error) { - comment := &model.Comment{ - Model: &model.Model{ +func (s *commentServant) GetCommentByID(id int64) (*core.Comment, error) { + comment := &dbr.Comment{ + Model: &dbr.Model{ ID: id, }, } return comment.Get(s.db) } -func (s *commentServant) GetCommentReplyByID(id int64) (*model.CommentReply, error) { - reply := &model.CommentReply{ - Model: &model.Model{ +func (s *commentServant) GetCommentReplyByID(id int64) (*core.CommentReply, error) { + reply := &dbr.CommentReply{ + Model: &dbr.Model{ ID: id, }, } return reply.Get(s.db) } -func (s *commentServant) GetCommentCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Comment{}).Count(s.db, conditions) +func (s *commentServant) GetCommentCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Comment{}).Count(s.db, conditions) } -func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*model.CommentContent, error) { - commentContent := &model.CommentContent{} - return commentContent.List(s.db, &model.ConditionsT{ +func (s *commentServant) GetCommentContentsByIDs(ids []int64) ([]*core.CommentContent, error) { + commentContent := &dbr.CommentContent{} + return commentContent.List(s.db, &dbr.ConditionsT{ "comment_id IN ?": ids, }, 0, 0) } -func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentReplyFormated, error) { - CommentReply := &model.CommentReply{} - replies, err := CommentReply.List(s.db, &model.ConditionsT{ +func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*core.CommentReplyFormated, error) { + CommentReply := &dbr.CommentReply{} + replies, err := CommentReply.List(s.db, &dbr.ConditionsT{ "comment_id IN ?": ids, }, 0, 0) @@ -83,7 +87,7 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep if err != nil { return nil, err } - repliesFormated := []*model.CommentReplyFormated{} + repliesFormated := []*core.CommentReplyFormated{} for _, reply := range replies { replyFormated := reply.Format() for _, user := range users { @@ -101,22 +105,22 @@ func (s *commentServant) GetCommentRepliesByID(ids []int64) ([]*model.CommentRep return repliesFormated, nil } -func (s *commentManageServant) DeleteComment(comment *model.Comment) error { +func (s *commentManageServant) DeleteComment(comment *core.Comment) error { return comment.Delete(s.db) } -func (s *commentManageServant) CreateComment(comment *model.Comment) (*model.Comment, error) { +func (s *commentManageServant) CreateComment(comment *core.Comment) (*core.Comment, error) { return comment.Create(s.db) } -func (s *commentManageServant) CreateCommentReply(reply *model.CommentReply) (*model.CommentReply, error) { +func (s *commentManageServant) CreateCommentReply(reply *core.CommentReply) (*core.CommentReply, error) { return reply.Create(s.db) } -func (s *commentManageServant) DeleteCommentReply(reply *model.CommentReply) error { +func (s *commentManageServant) DeleteCommentReply(reply *core.CommentReply) error { return reply.Delete(s.db) } -func (s *commentManageServant) CreateCommentContent(content *model.CommentContent) (*model.CommentContent, error) { +func (s *commentManageServant) CreateCommentContent(content *core.CommentContent) (*core.CommentContent, error) { return content.Create(s.db) } diff --git a/internal/dao/jinzhu/contacts.go b/internal/dao/jinzhu/contacts.go index c55a94a0..c26ae4de 100644 --- a/internal/dao/jinzhu/contacts.go +++ b/internal/dao/jinzhu/contacts.go @@ -1,11 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/sirupsen/logrus" "gorm.io/gorm" ) @@ -24,14 +27,14 @@ func newContactManageService(db *gorm.DB) core.ContactManageService { } } -func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*model.Contact, error) { - contact := &model.Contact{ +func (s *contactManageServant) fetchOrNewContact(db *gorm.DB, userId int64, friendId int64, status int8) (*dbr.Contact, error) { + contact := &dbr.Contact{ UserId: userId, FriendId: friendId, } contact, err := contact.FetchUser(db) if err != nil { - contact = &model.Contact{ + contact = &dbr.Contact{ UserId: userId, FriendId: friendId, Status: status, @@ -54,17 +57,17 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr } }() - contact, e := s.fetchOrNewContact(db, userId, friendId, model.ContactStatusRequesting) + contact, e := s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusRequesting) if e != nil { err = e return } // 如果已经好友,啥也不干 - if contact.Status == model.ContactStatusAgree { + if contact.Status == dbr.ContactStatusAgree { return nil - } else if contact.Status == model.ContactStatusReject || contact.Status == model.ContactStatusDeleted { - contact.Status = model.ContactStatusRequesting + } else if contact.Status == dbr.ContactStatusReject || contact.Status == dbr.ContactStatusDeleted { + contact.Status = dbr.ContactStatusRequesting contact.IsDel = 0 // remove deleted flag if needed if err = contact.UpdateInUnscoped(db); err != nil { logrus.Errorf("contactManageServant.RequestingFriend update exsit contact err:%s", err) @@ -72,13 +75,13 @@ func (s *contactManageServant) RequestingFriend(userId int64, friendId int64, gr } } - msg := &model.Message{ + msg := &dbr.Message{ SenderUserID: userId, ReceiverUserID: friendId, - Type: model.MsgTypeRequestingFriend, + Type: dbr.MsgTypeRequestingFriend, Brief: "请求添加好友,并附言:", Content: greetings, - ReplyID: int64(model.ContactStatusRequesting), + ReplyID: int64(dbr.ContactStatusRequesting), } if _, err = msg.Create(db); err != nil { logrus.Errorf("contactManageServant.RequestingFriend create message err:%s", err) @@ -97,7 +100,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } @@ -105,23 +108,23 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro return } // 如果还不是请求好友,啥也不干 - if contact.Status != model.ContactStatusRequesting { + if contact.Status != dbr.ContactStatusRequesting { logrus.Debugf("contactManageServant.AddFriend not reuesting status now so skip") return nil } - contact.Status = model.ContactStatusAgree + contact.Status = dbr.ContactStatusAgree if err = contact.Update(db); err != nil { return err } - contact, err = s.fetchOrNewContact(db, userId, friendId, model.ContactStatusAgree) + contact, err = s.fetchOrNewContact(db, userId, friendId, dbr.ContactStatusAgree) if err != nil { return } // 如果已经好友,啥也不干 - if contact.Status != model.ContactStatusAgree { - contact.Status = model.ContactStatusAgree + if contact.Status != dbr.ContactStatusAgree { + contact.Status = dbr.ContactStatusAgree contact.IsDel = 0 // remove deleted flag if err = contact.UpdateInUnscoped(db); err != nil { logrus.Errorf("contactManageServant.AddFriend update contact err:%s", err) @@ -129,8 +132,8 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro } } - args := []any{userId, friendId, friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting} - msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{ + args := []any{userId, friendId, friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting} + msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{ "((sender_user_id = ? AND receiver_user_id = ?) OR (sender_user_id = ? AND receiver_user_id = ?)) AND type = ? AND reply_id = ?": args, }) if e != nil { @@ -138,7 +141,7 @@ func (s *contactManageServant) AddFriend(userId int64, friendId int64) (err erro return } for _, msg := range msgs { - msg.ReplyID = int64(model.ContactStatusAgree) + msg.ReplyID = int64(dbr.ContactStatusAgree) if err = msg.Update(db); err != nil { return } @@ -156,7 +159,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } @@ -164,16 +167,16 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e return } // 如果还不是请求好友,啥也不干 - if contact.Status != model.ContactStatusRequesting { + if contact.Status != dbr.ContactStatusRequesting { return nil } - contact.Status = model.ContactStatusReject + contact.Status = dbr.ContactStatusReject if err = contact.Update(db); err != nil { return err } - args := []any{friendId, userId, model.MsgTypeRequestingFriend, model.ContactStatusRequesting} - msgs, e := (&model.Message{}).FetchBy(db, model.Predicates{ + args := []any{friendId, userId, dbr.MsgTypeRequestingFriend, dbr.ContactStatusRequesting} + msgs, e := (&dbr.Message{}).FetchBy(db, dbr.Predicates{ "sender_user_id = ? AND receiver_user_id = ? AND type = ? AND reply_id = ?": args, }) if e != nil { @@ -181,7 +184,7 @@ func (s *contactManageServant) RejectFriend(userId int64, friendId int64) (err e return } for _, msg := range msgs { - msg.ReplyID = int64(model.ContactStatusReject) + msg.ReplyID = int64(dbr.ContactStatusReject) if err = msg.Update(db); err != nil { return } @@ -199,7 +202,7 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e } }() - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: userId, FriendId: friendId, } @@ -210,10 +213,10 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e for _, contact := range contacts { // 如果还不是好友,啥也不干 - if contact.Status != model.ContactStatusAgree { + if contact.Status != dbr.ContactStatusAgree { continue } - contact.Status = model.ContactStatusDeleted + contact.Status = dbr.ContactStatusDeleted contact.DeletedOn = time.Now().Unix() contact.IsDel = 1 if err = contact.Update(db); err != nil { @@ -223,11 +226,11 @@ func (s *contactManageServant) DeleteFriend(userId int64, friendId int64) (err e return nil } -func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*rest.ContactsResp, error) { - contact := &model.Contact{} - condition := model.ConditionsT{ +func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) (*core.ContactList, error) { + contact := &dbr.Contact{} + condition := dbr.ConditionsT{ "user_id": userId, - "status": model.ContactStatusAgree, + "status": dbr.ContactStatusAgree, } contacts, err := contact.List(s.db, condition, offset, limit) if err != nil { @@ -237,13 +240,13 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) if err != nil { return nil, err } - resp := &rest.ContactsResp{ - Contacts: make([]rest.ContactItem, 0, len(contacts)), + resp := &core.ContactList{ + Contacts: make([]core.ContactItem, 0, len(contacts)), Total: total, } for _, c := range contacts { if c.User != nil { - resp.Contacts = append(resp.Contacts, rest.ContactItem{ + resp.Contacts = append(resp.Contacts, core.ContactItem{ UserId: c.FriendId, UserName: c.User.Username, Nickname: c.User.Nickname, @@ -256,12 +259,12 @@ func (s *contactManageServant) GetContacts(userId int64, offset int, limit int) } func (s *contactManageServant) IsFriend(userId int64, friendId int64) bool { - contact := &model.Contact{ + contact := &dbr.Contact{ UserId: friendId, FriendId: userId, } contact, err := contact.GetByUserFriend(s.db) - if err == nil && contact.Status == model.ContactStatusAgree { + if err == nil && contact.Status == dbr.ContactStatusAgree { return true } return false diff --git a/internal/model/attachment.go b/internal/dao/jinzhu/dbr/attachment.go similarity index 65% rename from internal/model/attachment.go rename to internal/dao/jinzhu/dbr/attachment.go index 0c748b00..b62a5d8b 100644 --- a/internal/model/attachment.go +++ b/internal/dao/jinzhu/dbr/attachment.go @@ -1,13 +1,17 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" type AttachmentType int const ( - ATTACHMENT_TYPE_IMAGE AttachmentType = iota + 1 - ATTACHMENT_TYPE_VIDEO - ATTACHMENT_TYPE_OTHER + AttachmentTypeImage AttachmentType = iota + 1 + AttachmentTypeVideo + AttachmentTypeOther ) type Attachment struct { diff --git a/internal/model/captcha.go b/internal/dao/jinzhu/dbr/captcha.go similarity index 82% rename from internal/model/captcha.go rename to internal/dao/jinzhu/dbr/captcha.go index 210cc691..4567d4b3 100644 --- a/internal/model/captcha.go +++ b/internal/dao/jinzhu/dbr/captcha.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/comment.go b/internal/dao/jinzhu/dbr/comment.go similarity index 94% rename from internal/model/comment.go rename to internal/dao/jinzhu/dbr/comment.go index 72494b53..80192df7 100644 --- a/internal/model/comment.go +++ b/internal/dao/jinzhu/dbr/comment.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/comment_content.go b/internal/dao/jinzhu/dbr/comment_content.go similarity index 85% rename from internal/model/comment_content.go rename to internal/dao/jinzhu/dbr/comment_content.go index b7d42dfd..778f113a 100644 --- a/internal/model/comment_content.go +++ b/internal/dao/jinzhu/dbr/comment_content.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" @@ -47,7 +51,7 @@ func (c *CommentContent) Create(db *gorm.DB) (*CommentContent, error) { } func (c *CommentContent) MediaContentsByCommentId(db *gorm.DB, commentIds []int64) (contents []string, err error) { - err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, CONTENT_TYPE_IMAGE).Select("content").Find(&contents).Error + err = db.Model(c).Where("comment_id IN ? AND type = ?", commentIds, ContentTypeImage).Select("content").Find(&contents).Error return } diff --git a/internal/model/comment_reply.go b/internal/dao/jinzhu/dbr/comment_reply.go similarity index 94% rename from internal/model/comment_reply.go rename to internal/dao/jinzhu/dbr/comment_reply.go index fd22702f..fe527be5 100644 --- a/internal/model/comment_reply.go +++ b/internal/dao/jinzhu/dbr/comment_reply.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/contact.go b/internal/dao/jinzhu/dbr/contact.go similarity index 95% rename from internal/model/contact.go rename to internal/dao/jinzhu/dbr/contact.go index 14049f77..e8c12bd0 100644 --- a/internal/model/contact.go +++ b/internal/dao/jinzhu/dbr/contact.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "github.com/sirupsen/logrus" diff --git a/internal/model/message.go b/internal/dao/jinzhu/dbr/message.go similarity index 95% rename from internal/model/message.go rename to internal/dao/jinzhu/dbr/message.go index c1277cf7..6c952bae 100644 --- a/internal/model/message.go +++ b/internal/dao/jinzhu/dbr/message.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/model.go b/internal/dao/jinzhu/dbr/model.go similarity index 83% rename from internal/model/model.go rename to internal/dao/jinzhu/dbr/model.go index 99bc8296..75e66561 100644 --- a/internal/model/model.go +++ b/internal/dao/jinzhu/dbr/model.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/post.go b/internal/dao/jinzhu/dbr/post.go similarity index 97% rename from internal/model/post.go rename to internal/dao/jinzhu/dbr/post.go index ae428a9a..a47dedfc 100644 --- a/internal/model/post.go +++ b/internal/dao/jinzhu/dbr/post.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "strings" diff --git a/internal/model/post_attachment_bill.go b/internal/dao/jinzhu/dbr/post_attachment_bill.go similarity index 81% rename from internal/model/post_attachment_bill.go rename to internal/dao/jinzhu/dbr/post_attachment_bill.go index 8ee7aae6..7bdd812f 100644 --- a/internal/model/post_attachment_bill.go +++ b/internal/dao/jinzhu/dbr/post_attachment_bill.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/post_collection.go b/internal/dao/jinzhu/dbr/post_collection.go similarity index 93% rename from internal/model/post_collection.go rename to internal/dao/jinzhu/dbr/post_collection.go index 0ea0cb29..04ca2647 100644 --- a/internal/model/post_collection.go +++ b/internal/dao/jinzhu/dbr/post_collection.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/post_content.go b/internal/dao/jinzhu/dbr/post_content.go similarity index 83% rename from internal/model/post_content.go rename to internal/dao/jinzhu/dbr/post_content.go index b301de62..672cc57e 100644 --- a/internal/model/post_content.go +++ b/internal/dao/jinzhu/dbr/post_content.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" @@ -7,27 +11,26 @@ import ( ) // 类型,1标题,2文字段落,3图片地址,4视频地址,5语音地址,6链接地址,7附件资源 - type PostContentT int const ( - CONTENT_TYPE_TITLE PostContentT = iota + 1 - CONTENT_TYPE_TEXT - CONTENT_TYPE_IMAGE - CONTENT_TYPE_VIDEO - CONTENT_TYPE_AUDIO - CONTENT_TYPE_LINK - CONTENT_TYPE_ATTACHMENT - CONTENT_TYPE_CHARGE_ATTACHMENT + ContentTypeTitle PostContentT = iota + 1 + ContentTypeText + ContentTypeImage + ContentTypeVideo + ContentTypeAudio + ContentTypeLink + ContentTypeAttachment + ContentTypeChargeAttachment ) var ( mediaContentType = []PostContentT{ - CONTENT_TYPE_IMAGE, - CONTENT_TYPE_VIDEO, - CONTENT_TYPE_AUDIO, - CONTENT_TYPE_ATTACHMENT, - CONTENT_TYPE_CHARGE_ATTACHMENT, + ContentTypeImage, + ContentTypeVideo, + ContentTypeAudio, + ContentTypeAttachment, + ContentTypeChargeAttachment, } ) diff --git a/internal/model/post_star.go b/internal/dao/jinzhu/dbr/post_star.go similarity index 93% rename from internal/model/post_star.go rename to internal/dao/jinzhu/dbr/post_star.go index 3846a9c2..45c48f45 100644 --- a/internal/model/post_star.go +++ b/internal/dao/jinzhu/dbr/post_star.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/tag.go b/internal/dao/jinzhu/dbr/tag.go similarity index 92% rename from internal/model/tag.go rename to internal/dao/jinzhu/dbr/tag.go index 34bb64f9..5193df26 100644 --- a/internal/model/tag.go +++ b/internal/dao/jinzhu/dbr/tag.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import ( "time" diff --git a/internal/model/user.go b/internal/dao/jinzhu/dbr/user.go similarity index 92% rename from internal/model/user.go rename to internal/dao/jinzhu/dbr/user.go index 39c52d79..a10d5432 100644 --- a/internal/model/user.go +++ b/internal/dao/jinzhu/dbr/user.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/wallet_recharge.go b/internal/dao/jinzhu/dbr/wallet_recharge.go similarity index 80% rename from internal/model/wallet_recharge.go rename to internal/dao/jinzhu/dbr/wallet_recharge.go index bfb3bc6f..14601cb0 100644 --- a/internal/model/wallet_recharge.go +++ b/internal/dao/jinzhu/dbr/wallet_recharge.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/model/wallet_statement.go b/internal/dao/jinzhu/dbr/wallet_statement.go similarity index 91% rename from internal/model/wallet_statement.go rename to internal/dao/jinzhu/dbr/wallet_statement.go index 163e2430..890e34ec 100644 --- a/internal/model/wallet_statement.go +++ b/internal/dao/jinzhu/dbr/wallet_statement.go @@ -1,4 +1,8 @@ -package model +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package dbr import "gorm.io/gorm" diff --git a/internal/dao/jinzhu/index.go b/internal/dao/jinzhu/index.go index 31712c61..7548de49 100644 --- a/internal/dao/jinzhu/index.go +++ b/internal/dao/jinzhu/index.go @@ -1,9 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/sirupsen/logrus" "gorm.io/gorm" ) @@ -40,20 +43,20 @@ func newSimpleIndexPostsService(db *gorm.DB) core.IndexPostsService { } // IndexPosts 根据userId查询广场推文列表,简单做到不同用户的主页都是不同的; -func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - predicates := model.Predicates{ +func (s *indexPostsServant) IndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + predicates := dbr.Predicates{ "ORDER": []any{"is_top DESC, latest_replied_on DESC"}, } if user == nil { - predicates["visibility = ?"] = []any{model.PostVisitPublic} + predicates["visibility = ?"] = []any{dbr.PostVisitPublic} } else if !user.IsAdmin { friendIds, _ := s.ams.BeFriendIds(user.ID) friendIds = append(friendIds, user.ID) - args := []any{model.PostVisitPublic, model.PostVisitPrivate, user.ID, model.PostVisitFriend, friendIds} + args := []any{dbr.PostVisitPublic, dbr.PostVisitPrivate, user.ID, dbr.PostVisitFriend, friendIds} predicates["visibility = ? OR (visibility = ? AND user_id = ?) OR (visibility = ? AND user_id IN ?)"] = args } - posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit) + posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit) if err != nil { logrus.Debugf("gormIndexPostsServant.IndexPosts err: %v", err) return nil, err @@ -63,25 +66,25 @@ func (s *indexPostsServant) IndexPosts(user *model.User, offset int, limit int) return nil, err } - total, err := (&model.Post{}).CountBy(s.db, predicates) + total, err := (&dbr.Post{}).CountBy(s.db, predicates) if err != nil { return nil, err } - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: formatPosts, Total: total, }, nil } // simpleCacheIndexGetPosts simpleCacheIndex 专属获取广场推文列表函数 -func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { - predicates := model.Predicates{ - "visibility = ?": []any{model.PostVisitPublic}, +func (s *simpleIndexPostsServant) IndexPosts(_user *core.User, offset int, limit int) (*core.IndexTweetList, error) { + predicates := dbr.Predicates{ + "visibility = ?": []any{dbr.PostVisitPublic}, "ORDER": []any{"is_top DESC, latest_replied_on DESC"}, } - posts, err := (&model.Post{}).Fetch(s.db, predicates, offset, limit) + posts, err := (&dbr.Post{}).Fetch(s.db, predicates, offset, limit) if err != nil { logrus.Debugf("gormSimpleIndexPostsServant.IndexPosts err: %v", err) return nil, err @@ -92,12 +95,12 @@ func (s *simpleIndexPostsServant) IndexPosts(_user *model.User, offset int, limi return nil, err } - total, err := (&model.Post{}).CountBy(s.db, predicates) + total, err := (&dbr.Post{}).CountBy(s.db, predicates) if err != nil { return nil, err } - return &rest.IndexTweetsResp{ + return &core.IndexTweetList{ Tweets: formatPosts, Total: total, }, nil diff --git a/internal/dao/jinzhu/jinzhu.go b/internal/dao/jinzhu/jinzhu.go index 9f5e1c66..753bb639 100644 --- a/internal/dao/jinzhu/jinzhu.go +++ b/internal/dao/jinzhu/jinzhu.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base gorm+mysql/postgresql/sqlite3. // Jinzhu is the primary developer of gorm so use his name as // package name as a saluter. diff --git a/internal/dao/jinzhu/messages.go b/internal/dao/jinzhu/messages.go index 3e282776..32edaac2 100644 --- a/internal/dao/jinzhu/messages.go +++ b/internal/dao/jinzhu/messages.go @@ -1,8 +1,12 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -20,37 +24,37 @@ func newMessageService(db *gorm.DB) core.MessageService { } } -func (d *messageServant) CreateMessage(msg *model.Message) (*model.Message, error) { +func (d *messageServant) CreateMessage(msg *core.Message) (*core.Message, error) { return msg.Create(d.db) } func (d *messageServant) GetUnreadCount(userID int64) (int64, error) { - return (&model.Message{}).Count(d.db, &model.ConditionsT{ + return (&dbr.Message{}).Count(d.db, &dbr.ConditionsT{ "receiver_user_id": userID, - "is_read": model.MsgStatusUnread, + "is_read": dbr.MsgStatusUnread, }) } -func (d *messageServant) GetMessageByID(id int64) (*model.Message, error) { - return (&model.Message{ - Model: &model.Model{ +func (d *messageServant) GetMessageByID(id int64) (*core.Message, error) { + return (&dbr.Message{ + Model: &dbr.Model{ ID: id, }, }).Get(d.db) } -func (d *messageServant) ReadMessage(message *model.Message) error { +func (d *messageServant) ReadMessage(message *core.Message) error { message.IsRead = 1 return message.Update(d.db) } -func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limit int) ([]*model.MessageFormated, error) { - messages, err := (&model.Message{}).List(d.db, conditions, offset, limit) +func (d *messageServant) GetMessages(conditions *core.ConditionsT, offset, limit int) ([]*core.MessageFormated, error) { + messages, err := (&dbr.Message{}).List(d.db, conditions, offset, limit) if err != nil { return nil, err } - mfs := []*model.MessageFormated{} + mfs := []*dbr.MessageFormated{} for _, message := range messages { mf := message.Format() mfs = append(mfs, mf) @@ -59,6 +63,6 @@ func (d *messageServant) GetMessages(conditions *model.ConditionsT, offset, limi return mfs, nil } -func (d *messageServant) GetMessageCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Message{}).Count(d.db, conditions) +func (d *messageServant) GetMessageCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Message{}).Count(d.db, conditions) } diff --git a/internal/dao/jinzhu/security.go b/internal/dao/jinzhu/security.go index dfbe2c74..49f66074 100644 --- a/internal/dao/jinzhu/security.go +++ b/internal/dao/jinzhu/security.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( @@ -10,7 +14,7 @@ import ( "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "github.com/rocboss/paopao-ce/pkg/json" "gopkg.in/resty.v1" "gorm.io/gorm" @@ -36,14 +40,14 @@ type juhePhoneCaptchaRsp struct { } // 获取最新短信验证码 -func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*model.Captcha, error) { - return (&model.Captcha{ +func (s *securityServant) GetLatestPhoneCaptcha(phone string) (*core.Captcha, error) { + return (&dbr.Captcha{ Phone: phone, }).Get(s.db) } // 更新短信验证码 -func (s *securityServant) UsePhoneCaptcha(captcha *model.Captcha) error { +func (s *securityServant) UsePhoneCaptcha(captcha *core.Captcha) error { captcha.UseTimes++ return captcha.Update(s.db) } @@ -82,7 +86,7 @@ func (s *securityServant) SendPhoneCaptcha(phone string) error { } // 写入表 - captchaModel := &model.Captcha{ + captchaModel := &dbr.Captcha{ Phone: phone, Captcha: strconv.Itoa(captcha), ExpiredOn: time.Now().Add(time.Minute * time.Duration(m)).Unix(), diff --git a/internal/dao/jinzhu/topics.go b/internal/dao/jinzhu/topics.go index 0524b71b..d5ce70a9 100644 --- a/internal/dao/jinzhu/topics.go +++ b/internal/dao/jinzhu/topics.go @@ -1,10 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "strings" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -22,28 +26,28 @@ func newTopicService(db *gorm.DB) core.TopicService { } } -func (s *topicServant) CreateTag(tag *model.Tag) (*model.Tag, error) { +func (s *topicServant) CreateTag(tag *core.Tag) (*core.Tag, error) { return createTag(s.db, tag) } -func (s *topicServant) DeleteTag(tag *model.Tag) error { +func (s *topicServant) DeleteTag(tag *core.Tag) error { return deleteTag(s.db, tag) } -func (s *topicServant) GetTags(conditions *model.ConditionsT, offset, limit int) ([]*model.Tag, error) { - return (&model.Tag{}).List(s.db, conditions, offset, limit) +func (s *topicServant) GetTags(conditions *core.ConditionsT, offset, limit int) ([]*core.Tag, error) { + return (&dbr.Tag{}).List(s.db, conditions, offset, limit) } -func (s *topicServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) { - tag := &model.Tag{} +func (s *topicServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) { + tag := &dbr.Tag{} keyword = "%" + strings.Trim(keyword, " ") + "%" if keyword == "%%" { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "ORDER": "quote_num DESC", }, 0, 6) } else { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "tag LIKE ?": keyword, "ORDER": "quote_num DESC", }, 0, 6) diff --git a/internal/dao/jinzhu/tweets.go b/internal/dao/jinzhu/tweets.go index 12e6f21c..186b7280 100644 --- a/internal/dao/jinzhu/tweets.go +++ b/internal/dao/jinzhu/tweets.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( @@ -5,7 +9,7 @@ import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -48,7 +52,7 @@ func newTweetHelpService(db *gorm.DB) core.TweetHelpService { } // MergePosts post数据整合 -func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormated, error) { +func (s *tweetHelpServant) MergePosts(posts []*core.Post) ([]*core.PostFormated, error) { postIds := make([]int64, 0, len(posts)) userIds := make([]int64, 0, len(posts)) for _, post := range posts { @@ -66,18 +70,18 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate return nil, err } - userMap := make(map[int64]*model.UserFormated, len(users)) + userMap := make(map[int64]*dbr.UserFormated, len(users)) for _, user := range users { userMap[user.ID] = user.Format() } - contentMap := make(map[int64][]*model.PostContentFormated, len(postContents)) + contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents)) for _, content := range postContents { contentMap[content.PostID] = append(contentMap[content.PostID], content.Format()) } // 数据整合 - postsFormated := make([]*model.PostFormated, 0, len(posts)) + postsFormated := make([]*dbr.PostFormated, 0, len(posts)) for _, post := range posts { postFormated := post.Format() postFormated.User = userMap[post.UserID] @@ -88,7 +92,7 @@ func (s *tweetHelpServant) MergePosts(posts []*model.Post) ([]*model.PostFormate } // RevampPosts post数据整形修复 -func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.PostFormated, error) { +func (s *tweetHelpServant) RevampPosts(posts []*core.PostFormated) ([]*core.PostFormated, error) { postIds := make([]int64, 0, len(posts)) userIds := make([]int64, 0, len(posts)) for _, post := range posts { @@ -106,12 +110,12 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po return nil, err } - userMap := make(map[int64]*model.UserFormated, len(users)) + userMap := make(map[int64]*dbr.UserFormated, len(users)) for _, user := range users { userMap[user.ID] = user.Format() } - contentMap := make(map[int64][]*model.PostContentFormated, len(postContents)) + contentMap := make(map[int64][]*dbr.PostContentFormated, len(postContents)) for _, content := range postContents { contentMap[content.PostID] = append(contentMap[content.PostID], content.Format()) } @@ -124,23 +128,23 @@ func (s *tweetHelpServant) RevampPosts(posts []*model.PostFormated) ([]*model.Po return posts, nil } -func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*model.PostContent, error) { - return (&model.PostContent{}).List(s.db, &model.ConditionsT{ +func (s *tweetHelpServant) getPostContentsByIDs(ids []int64) ([]*dbr.PostContent, error) { + return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{ "post_id IN ?": ids, "ORDER": "sort ASC", }, 0, 0) } -func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*model.User, error) { - user := &model.User{} +func (s *tweetHelpServant) getUsersByIDs(ids []int64) ([]*dbr.User, error) { + user := &dbr.User{} - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } -func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { - collection := &model.PostCollection{ +func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*core.PostCollection, error) { + collection := &dbr.PostCollection{ PostID: postID, UserID: userID, } @@ -148,19 +152,19 @@ func (s *tweetManageServant) CreatePostCollection(postID, userID int64) (*model. return collection.Create(s.db) } -func (s *tweetManageServant) DeletePostCollection(p *model.PostCollection) error { +func (s *tweetManageServant) DeletePostCollection(p *core.PostCollection) error { return p.Delete(s.db) } -func (s *tweetManageServant) CreatePostContent(content *model.PostContent) (*model.PostContent, error) { +func (s *tweetManageServant) CreatePostContent(content *core.PostContent) (*core.PostContent, error) { return content.Create(s.db) } -func (s *tweetManageServant) CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) { +func (s *tweetManageServant) CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) { return attachment.Create(s.db) } -func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) { +func (s *tweetManageServant) CreatePost(post *core.Post) (*core.Post, error) { post.LatestRepliedOn = time.Now().Unix() p, err := post.Create(s.db) if err != nil { @@ -170,11 +174,11 @@ func (s *tweetManageServant) CreatePost(post *model.Post) (*model.Post, error) { return p, nil } -func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) { +func (s *tweetManageServant) DeletePost(post *core.Post) ([]string, error) { var mediaContents []string postId := post.ID - postContent := &model.PostContent{} + postContent := &dbr.PostContent{} err := s.db.Transaction( func(tx *gorm.DB) error { if contents, err := postContent.MediaContentsByPostId(tx, postId); err == nil { @@ -218,8 +222,8 @@ func (s *tweetManageServant) DeletePost(post *model.Post) ([]string, error) { } func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([]string, error) { - comment := &model.Comment{} - commentContent := &model.CommentContent{} + comment := &dbr.Comment{} + commentContent := &dbr.CommentContent{} // 获取推文的所有评论id commentIds, err := comment.CommentIdsByPostId(db, postId) @@ -244,19 +248,19 @@ func (s *tweetManageServant) deleteCommentByPostId(db *gorm.DB, postId int64) ([ } // 删评论的评论 - if err = (&model.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil { + if err = (&dbr.CommentReply{}).DeleteByCommentIds(db, commentIds); err != nil { return nil, err } return mediaContents, nil } -func (s *tweetManageServant) LockPost(post *model.Post) error { +func (s *tweetManageServant) LockPost(post *core.Post) error { post.IsLock = 1 - post.IsLock return post.Update(s.db) } -func (s *tweetManageServant) StickPost(post *model.Post) error { +func (s *tweetManageServant) StickPost(post *core.Post) error { post.IsTop = 1 - post.IsTop if err := post.Update(s.db); err != nil { return err @@ -265,7 +269,7 @@ func (s *tweetManageServant) StickPost(post *model.Post) error { return nil } -func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.PostVisibleT) error { +func (s *tweetManageServant) VisiblePost(post *core.Post, visibility core.PostVisibleT) error { oldVisibility := post.Visibility post.Visibility = visibility // TODO: 这个判断是否可以不要呢 @@ -273,7 +277,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post return nil } // 私密推文 特殊处理 - if visibility == model.PostVisitPrivate { + if visibility == dbr.PostVisitPrivate { // 强制取消置顶 // TODO: 置顶推文用户是否有权设置成私密? 后续完善 post.IsTop = 0 @@ -288,14 +292,14 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post // tag处理 tags := strings.Split(post.Tags, ",") for _, t := range tags { - tag := &model.Tag{ + tag := &dbr.Tag{ Tag: t, } // TODO: 暂时宽松不处理错误,这里或许可以有优化,后续完善 - if oldVisibility == model.PostVisitPrivate { + if oldVisibility == dbr.PostVisitPrivate { // 从私密转为非私密才需要重新创建tag createTag(db, tag) - } else if visibility == model.PostVisitPrivate { + } else if visibility == dbr.PostVisitPrivate { // 从非私密转为私密才需要删除tag deleteTag(db, tag) } @@ -305,7 +309,7 @@ func (s *tweetManageServant) VisiblePost(post *model.Post, visibility model.Post return nil } -func (s *tweetManageServant) UpdatePost(post *model.Post) error { +func (s *tweetManageServant) UpdatePost(post *core.Post) error { if err := post.Update(s.db); err != nil { return err } @@ -313,104 +317,104 @@ func (s *tweetManageServant) UpdatePost(post *model.Post) error { return nil } -func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetManageServant) CreatePostStar(postID, userID int64) (*core.PostStar, error) { + star := &dbr.PostStar{ PostID: postID, UserID: userID, } return star.Create(s.db) } -func (s *tweetManageServant) DeletePostStar(p *model.PostStar) error { +func (s *tweetManageServant) DeletePostStar(p *core.PostStar) error { return p.Delete(s.db) } -func (s *tweetServant) GetPostByID(id int64) (*model.Post, error) { - post := &model.Post{ - Model: &model.Model{ +func (s *tweetServant) GetPostByID(id int64) (*core.Post, error) { + post := &dbr.Post{ + Model: &dbr.Model{ ID: id, }, } return post.Get(s.db) } -func (s *tweetServant) GetPosts(conditions *model.ConditionsT, offset, limit int) ([]*model.Post, error) { - return (&model.Post{}).List(s.db, conditions, offset, limit) +func (s *tweetServant) GetPosts(conditions *core.ConditionsT, offset, limit int) ([]*core.Post, error) { + return (&dbr.Post{}).List(s.db, conditions, offset, limit) } -func (s *tweetServant) GetPostCount(conditions *model.ConditionsT) (int64, error) { - return (&model.Post{}).Count(s.db, conditions) +func (s *tweetServant) GetPostCount(conditions *core.ConditionsT) (int64, error) { + return (&dbr.Post{}).Count(s.db, conditions) } -func (s *tweetServant) GetUserPostStar(postID, userID int64) (*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetServant) GetUserPostStar(postID, userID int64) (*core.PostStar, error) { + star := &dbr.PostStar{ PostID: postID, UserID: userID, } return star.Get(s.db) } -func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*model.PostStar, error) { - star := &model.PostStar{ +func (s *tweetServant) GetUserPostStars(userID int64, offset, limit int) ([]*core.PostStar, error) { + star := &dbr.PostStar{ UserID: userID, } - return star.List(s.db, &model.ConditionsT{ + return star.List(s.db, &dbr.ConditionsT{ "ORDER": s.db.NamingStrategy.TableName("PostStar") + ".id DESC", }, offset, limit) } func (s *tweetServant) GetUserPostStarCount(userID int64) (int64, error) { - star := &model.PostStar{ + star := &dbr.PostStar{ UserID: userID, } - return star.Count(s.db, &model.ConditionsT{}) + return star.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*model.PostCollection, error) { - star := &model.PostCollection{ +func (s *tweetServant) GetUserPostCollection(postID, userID int64) (*core.PostCollection, error) { + star := &dbr.PostCollection{ PostID: postID, UserID: userID, } return star.Get(s.db) } -func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*model.PostCollection, error) { - collection := &model.PostCollection{ +func (s *tweetServant) GetUserPostCollections(userID int64, offset, limit int) ([]*core.PostCollection, error) { + collection := &dbr.PostCollection{ UserID: userID, } - return collection.List(s.db, &model.ConditionsT{ + return collection.List(s.db, &dbr.ConditionsT{ "ORDER": s.db.NamingStrategy.TableName("PostCollection") + ".id DESC", }, offset, limit) } func (s *tweetServant) GetUserPostCollectionCount(userID int64) (int64, error) { - collection := &model.PostCollection{ + collection := &dbr.PostCollection{ UserID: userID, } - return collection.Count(s.db, &model.ConditionsT{}) + return collection.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) { - statement := &model.WalletStatement{ +func (s *tweetServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) { + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.List(s.db, &model.ConditionsT{ + return statement.List(s.db, &dbr.ConditionsT{ "ORDER": "id DESC", }, offset, limit) } func (s *tweetServant) GetUserWalletBillCount(userID int64) (int64, error) { - statement := &model.WalletStatement{ + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.Count(s.db, &model.ConditionsT{}) + return statement.Count(s.db, &dbr.ConditionsT{}) } -func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.PostAttachmentBill, error) { - bill := &model.PostAttachmentBill{ +func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*core.PostAttachmentBill, error) { + bill := &dbr.PostAttachmentBill{ PostID: postID, UserID: userID, } @@ -418,16 +422,16 @@ func (s *tweetServant) GetPostAttatchmentBill(postID, userID int64) (*model.Post return bill.Get(s.db) } -func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*model.PostContent, error) { - return (&model.PostContent{}).List(s.db, &model.ConditionsT{ +func (s *tweetServant) GetPostContentsByIDs(ids []int64) ([]*core.PostContent, error) { + return (&dbr.PostContent{}).List(s.db, &dbr.ConditionsT{ "post_id IN ?": ids, "ORDER": "sort ASC", }, 0, 0) } -func (s *tweetServant) GetPostContentByID(id int64) (*model.PostContent, error) { - return (&model.PostContent{ - Model: &model.Model{ +func (s *tweetServant) GetPostContentByID(id int64) (*core.PostContent, error) { + return (&dbr.PostContent{ + Model: &dbr.Model{ ID: id, }, }).Get(s.db) diff --git a/internal/dao/jinzhu/user.go b/internal/dao/jinzhu/user.go index e1380f00..96d09fc1 100644 --- a/internal/dao/jinzhu/user.go +++ b/internal/dao/jinzhu/user.go @@ -1,10 +1,14 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "strings" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -22,69 +26,69 @@ func newUserManageService(db *gorm.DB) core.UserManageService { } } -func (s *userManageServant) GetUserByID(id int64) (*model.User, error) { - user := &model.User{ - Model: &model.Model{ +func (s *userManageServant) GetUserByID(id int64) (*core.User, error) { + user := &dbr.User{ + Model: &dbr.Model{ ID: id, }, } return user.Get(s.db) } -func (s *userManageServant) GetUserByUsername(username string) (*model.User, error) { - user := &model.User{ +func (s *userManageServant) GetUserByUsername(username string) (*core.User, error) { + user := &dbr.User{ Username: username, } return user.Get(s.db) } -func (s *userManageServant) GetUserByPhone(phone string) (*model.User, error) { - user := &model.User{ +func (s *userManageServant) GetUserByPhone(phone string) (*core.User, error) { + user := &dbr.User{ Phone: phone, } return user.Get(s.db) } -func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*model.User, error) { - user := &model.User{} - return user.List(s.db, &model.ConditionsT{ +func (s *userManageServant) GetUsersByIDs(ids []int64) ([]*core.User, error) { + user := &dbr.User{} + return user.List(s.db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } -func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*model.User, error) { - user := &model.User{} +func (s *userManageServant) GetUsersByKeyword(keyword string) ([]*core.User, error) { + user := &dbr.User{} keyword = strings.Trim(keyword, " ") + "%" if keyword == "%" { - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "ORDER": "id ASC", }, 0, 6) } else { - return user.List(s.db, &model.ConditionsT{ + return user.List(s.db, &dbr.ConditionsT{ "username LIKE ?": keyword, }, 0, 6) } } -func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*model.Tag, error) { - tag := &model.Tag{} +func (s *userManageServant) GetTagsByKeyword(keyword string) ([]*core.Tag, error) { + tag := &dbr.Tag{} keyword = "%" + strings.Trim(keyword, " ") + "%" if keyword == "%%" { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "ORDER": "quote_num DESC", }, 0, 6) } else { - return tag.List(s.db, &model.ConditionsT{ + return tag.List(s.db, &dbr.ConditionsT{ "tag LIKE ?": keyword, "ORDER": "quote_num DESC", }, 0, 6) } } -func (s *userManageServant) CreateUser(user *model.User) (*model.User, error) { +func (s *userManageServant) CreateUser(user *dbr.User) (*core.User, error) { return user.Create(s.db) } -func (s *userManageServant) UpdateUser(user *model.User) error { +func (s *userManageServant) UpdateUser(user *core.User) error { return user.Update(s.db) } diff --git a/internal/dao/jinzhu/utils.go b/internal/dao/jinzhu/utils.go index 8c866027..27766397 100644 --- a/internal/dao/jinzhu/utils.go +++ b/internal/dao/jinzhu/utils.go @@ -1,11 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) -func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) { +func createTag(db *gorm.DB, tag *dbr.Tag) (*dbr.Tag, error) { t, err := tag.Get(db) if err != nil { tag.QuoteNum = 1 @@ -23,7 +27,7 @@ func createTag(db *gorm.DB, tag *model.Tag) (*model.Tag, error) { return t, nil } -func deleteTag(db *gorm.DB, tag *model.Tag) error { +func deleteTag(db *gorm.DB, tag *dbr.Tag) error { tag, err := tag.Get(db) if err != nil { return err @@ -33,7 +37,7 @@ func deleteTag(db *gorm.DB, tag *model.Tag) error { } func deleteTags(db *gorm.DB, tags []string) error { - allTags, err := (&model.Tag{}).TagsFrom(db, tags) + allTags, err := (&dbr.Tag{}).TagsFrom(db, tags) if err != nil { return err } @@ -51,9 +55,9 @@ func deleteTags(db *gorm.DB, tags []string) error { } // 根据IDs获取用户列表 -func getUsersByIDs(db *gorm.DB, ids []int64) ([]*model.User, error) { - user := &model.User{} - return user.List(db, &model.ConditionsT{ +func getUsersByIDs(db *gorm.DB, ids []int64) ([]*dbr.User, error) { + user := &dbr.User{} + return user.List(db, &dbr.ConditionsT{ "id IN ?": ids, }, 0, 0) } diff --git a/internal/dao/jinzhu/wallet.go b/internal/dao/jinzhu/wallet.go index 3b4f9ea1..7b2023d7 100644 --- a/internal/dao/jinzhu/wallet.go +++ b/internal/dao/jinzhu/wallet.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package jinzhu import ( "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/dao/jinzhu/dbr" "gorm.io/gorm" ) @@ -21,17 +25,17 @@ func newWalletService(db *gorm.DB) core.WalletService { } } -func (d *walletServant) GetRechargeByID(id int64) (*model.WalletRecharge, error) { - recharge := &model.WalletRecharge{ - Model: &model.Model{ +func (d *walletServant) GetRechargeByID(id int64) (*core.WalletRecharge, error) { + recharge := &dbr.WalletRecharge{ + Model: &dbr.Model{ ID: id, }, } return recharge.Get(d.db) } -func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecharge, error) { - recharge := &model.WalletRecharge{ +func (d *walletServant) CreateRecharge(userId, amount int64) (*core.WalletRecharge, error) { + recharge := &dbr.WalletRecharge{ UserID: userId, Amount: amount, } @@ -39,26 +43,26 @@ func (d *walletServant) CreateRecharge(userId, amount int64) (*model.WalletRecha return recharge.Create(d.db) } -func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, error) { - statement := &model.WalletStatement{ +func (d *walletServant) GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, error) { + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.List(d.db, &model.ConditionsT{ + return statement.List(d.db, &dbr.ConditionsT{ "ORDER": "id DESC", }, offset, limit) } func (d *walletServant) GetUserWalletBillCount(userID int64) (int64, error) { - statement := &model.WalletStatement{ + statement := &dbr.WalletStatement{ UserID: userID, } - return statement.Count(d.db, &model.ConditionsT{}) + return statement.Count(d.db, &dbr.ConditionsT{}) } -func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tradeNo string) error { - user, _ := (&model.User{ - Model: &model.Model{ +func (d *walletServant) HandleRechargeSuccess(recharge *core.WalletRecharge, tradeNo string) error { + user, _ := (&dbr.User{ + Model: &dbr.Model{ ID: recharge.UserID, }, }).Get(d.db) @@ -71,7 +75,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ UserID: user.ID, ChangeAmount: recharge.Amount, BalanceSnapshot: user.Balance + recharge.Amount, @@ -93,7 +97,7 @@ func (d *walletServant) HandleRechargeSuccess(recharge *model.WalletRecharge, tr }) } -func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model.User) error { +func (d *walletServant) HandlePostAttachmentBought(post *core.Post, user *core.User) error { return d.db.Transaction(func(tx *gorm.DB) error { // 扣除金额 if err := tx.Model(user).Update("balance", gorm.Expr("balance - ?", post.AttachmentPrice)).Error; err != nil { @@ -102,7 +106,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ PostID: post.ID, UserID: user.ID, ChangeAmount: -post.AttachmentPrice, @@ -113,7 +117,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增附件购买记录 - if err := tx.Create(&model.PostAttachmentBill{ + if err := tx.Create(&dbr.PostAttachmentBill{ PostID: post.ID, UserID: user.ID, PaidAmount: post.AttachmentPrice, @@ -124,8 +128,8 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model // 对附件主新增账单 income := int64(float64(post.AttachmentPrice) * conf.AppSetting.AttachmentIncomeRate) if income > 0 { - master := &model.User{ - Model: &model.Model{ + master := &dbr.User{ + Model: &dbr.Model{ ID: post.UserID, }, } @@ -137,7 +141,7 @@ func (d *walletServant) HandlePostAttachmentBought(post *model.Post, user *model } // 新增账单 - if err := tx.Create(&model.WalletStatement{ + if err := tx.Create(&dbr.WalletStatement{ PostID: post.ID, UserID: master.ID, ChangeAmount: income, diff --git a/internal/dao/sakila/sakila.go b/internal/dao/sakila/sakila.go index 6efdffa6..d82a0d23 100644 --- a/internal/dao/sakila/sakila.go +++ b/internal/dao/sakila/sakila.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base sqlx+mysql. All sub-service // will declare here and provide initial function. diff --git a/internal/dao/search/bridge.go b/internal/dao/search/bridge.go index 84f469a5..f23aaa25 100644 --- a/internal/dao/search/bridge.go +++ b/internal/dao/search/bridge.go @@ -1,10 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( "time" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/sirupsen/logrus" ) @@ -43,7 +46,7 @@ func (s *bridgeTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *bridgeTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *bridgeTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { return s.ts.Search(user, q, offset, limit) } diff --git a/internal/dao/search/filter.go b/internal/dao/search/filter.go index 229f2482..5840e189 100644 --- a/internal/dao/search/filter.go +++ b/internal/dao/search/filter.go @@ -1,8 +1,11 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/types" ) @@ -10,19 +13,19 @@ type tweetSearchFilter struct { ams core.AuthorizationManageService } -func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) { +func (s *tweetSearchFilter) filterResp(user *core.User, resp *core.QueryResp) { // 管理员不过滤 if user != nil && user.IsAdmin { return } - var item *model.PostFormated + var item *core.PostFormated items := resp.Items latestIndex := len(items) - 1 if user == nil { for i := 0; i <= latestIndex; i++ { item = items[i] - if item.Visibility != model.PostVisitPublic { + if item.Visibility != core.PostVisitPublic { items[i] = items[latestIndex] items = items[:latestIndex] resp.Total-- @@ -36,8 +39,8 @@ func (s *tweetSearchFilter) filterResp(user *model.User, resp *core.QueryResp) { friendFilter[user.ID] = types.Empty{} for i := 0; i <= latestIndex; i++ { item = items[i] - cutFriend = (item.Visibility == model.PostVisitFriend && !friendFilter.IsFriend(item.UserID)) - cutPrivate = (item.Visibility == model.PostVisitPrivate && user.ID != item.UserID) + cutFriend = (item.Visibility == core.PostVisitFriend && !friendFilter.IsFriend(item.UserID)) + cutPrivate = (item.Visibility == core.PostVisitPrivate && user.ID != item.UserID) if cutFriend || cutPrivate { items[i] = items[latestIndex] items = items[:latestIndex] diff --git a/internal/dao/search/meili.go b/internal/dao/search/meili.go index 321953ee..b2ee4d16 100644 --- a/internal/dao/search/meili.go +++ b/internal/dao/search/meili.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -7,7 +11,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/meilisearch/meilisearch-go" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/json" "github.com/sirupsen/logrus" ) @@ -28,20 +31,20 @@ type meiliTweetSearchServant struct { } type postInfo struct { - ID int64 `json:"id"` - UserID int64 `json:"user_id"` - CommentCount int64 `json:"comment_count"` - CollectionCount int64 `json:"collection_count"` - UpvoteCount int64 `json:"upvote_count"` - Visibility model.PostVisibleT `json:"visibility"` - IsTop int `json:"is_top"` - IsEssence int `json:"is_essence"` - IsLock int `json:"is_lock"` - LatestRepliedOn int64 `json:"latest_replied_on"` - CreatedOn int64 `json:"created_on"` - ModifiedOn int64 `json:"modified_on"` - AttachmentPrice int64 `json:"attachment_price"` - IPLoc string `json:"ip_loc"` + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + CommentCount int64 `json:"comment_count"` + CollectionCount int64 `json:"collection_count"` + UpvoteCount int64 `json:"upvote_count"` + Visibility core.PostVisibleT `json:"visibility"` + IsTop int `json:"is_top"` + IsEssence int `json:"is_essence"` + IsLock int `json:"is_lock"` + LatestRepliedOn int64 `json:"latest_replied_on"` + CreatedOn int64 `json:"created_on"` + ModifiedOn int64 `json:"modified_on"` + AttachmentPrice int64 `json:"attachment_price"` + IPLoc string `json:"ip_loc"` } func (s *meiliTweetSearchServant) Name() string { @@ -78,7 +81,7 @@ func (s *meiliTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { +func (s *meiliTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { if q.Type == core.SearchTypeDefault && q.Query != "" { resp, err = s.queryByContent(user, q, offset, limit) } else if q.Type == core.SearchTypeTag && q.Query != "" { @@ -96,7 +99,7 @@ func (s *meiliTweetSearchServant) Search(user *model.User, q *core.QueryReq, off return } -func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -117,7 +120,7 @@ func (s *meiliTweetSearchServant) queryByContent(user *model.User, q *core.Query return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -141,7 +144,7 @@ func (s *meiliTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) { +func (s *meiliTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) { request := &meilisearch.SearchRequest{ Offset: int64(offset), Limit: int64(limit), @@ -161,7 +164,7 @@ func (s *meiliTweetSearchServant) queryAny(user *model.User, offset, limit int) return s.postsFrom(resp) } -func (s *meiliTweetSearchServant) filterList(user *model.User) string { +func (s *meiliTweetSearchServant) filterList(user *core.User) string { if user == nil { return s.publicFilter } @@ -174,7 +177,7 @@ func (s *meiliTweetSearchServant) filterList(user *model.User) string { } func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (*core.QueryResp, error) { - posts := make([]*model.PostFormated, 0, len(resp.Hits)) + posts := make([]*core.PostFormated, 0, len(resp.Hits)) for _, hit := range resp.Hits { raw, err := json.Marshal(hit) if err != nil { @@ -184,7 +187,7 @@ func (s *meiliTweetSearchServant) postsFrom(resp *meilisearch.SearchResponse) (* if err = json.Unmarshal(raw, p); err != nil { return nil, err } - posts = append(posts, &model.PostFormated{ + posts = append(posts, &core.PostFormated{ ID: p.ID, UserID: p.UserID, CommentCount: p.CommentCount, diff --git a/internal/dao/search/search.go b/internal/dao/search/search.go index 1dda80ef..baf0923b 100644 --- a/internal/dao/search/search.go +++ b/internal/dao/search/search.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -6,7 +10,6 @@ import ( "github.com/meilisearch/meilisearch-go" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/zinc" "github.com/sirupsen/logrus" ) @@ -40,9 +43,9 @@ func NewMeiliTweetSearchService(ams core.AuthorizationManageService) (core.Tweet }, client: client, index: client.Index(s.Index), - publicFilter: fmt.Sprintf("visibility=%d", model.PostVisitPublic), - privateFilter: fmt.Sprintf("visibility=%d AND user_id=", model.PostVisitPrivate), - friendFilter: fmt.Sprintf("visibility=%d", model.PostVisitFriend), + publicFilter: fmt.Sprintf("visibility=%d", core.PostVisitPublic), + privateFilter: fmt.Sprintf("visibility=%d AND user_id=", core.PostVisitPrivate), + friendFilter: fmt.Sprintf("visibility=%d", core.PostVisitFriend), } return mts, mts } @@ -55,9 +58,9 @@ func NewZincTweetSearchService(ams core.AuthorizationManageService) (core.TweetS }, indexName: s.Index, client: zinc.NewClient(s), - publicFilter: fmt.Sprintf("visibility:%d", model.PostVisitPublic), - privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", model.PostVisitPrivate), - friendFilter: fmt.Sprintf("visibility:%d", model.PostVisitFriend), + publicFilter: fmt.Sprintf("visibility:%d", core.PostVisitPublic), + privateFilter: fmt.Sprintf("visibility:%d AND user_id:%%d", core.PostVisitPrivate), + friendFilter: fmt.Sprintf("visibility:%d", core.PostVisitFriend), } zts.createIndex() diff --git a/internal/dao/search/zinc.go b/internal/dao/search/zinc.go index c038cb90..ea9a7fa5 100644 --- a/internal/dao/search/zinc.go +++ b/internal/dao/search/zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package search import ( @@ -5,7 +9,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/json" "github.com/rocboss/paopao-ce/pkg/zinc" "github.com/sirupsen/logrus" @@ -73,7 +76,7 @@ func (s *zincTweetSearchServant) DeleteDocuments(identifiers []string) error { return nil } -func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { +func (s *zincTweetSearchServant) Search(user *core.User, q *core.QueryReq, offset, limit int) (resp *core.QueryResp, err error) { if q.Type == core.SearchTypeDefault && q.Query != "" { resp, err = s.queryByContent(user, q, offset, limit) } else if q.Type == core.SearchTypeTag && q.Query != "" { @@ -91,7 +94,7 @@ func (s *zincTweetSearchServant) Search(user *model.User, q *core.QueryReq, offs return } -func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryByContent(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { resp, err := s.client.EsQuery(s.indexName, map[string]any{ "query": map[string]any{ "match_phrase": map[string]any{ @@ -108,7 +111,7 @@ func (s *zincTweetSearchServant) queryByContent(user *model.User, q *core.QueryR return s.postsFrom(resp) } -func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryByTag(user *core.User, q *core.QueryReq, offset, limit int) (*core.QueryResp, error) { resp, err := s.client.ApiQuery(s.indexName, map[string]any{ "search_type": "querystring", "query": map[string]any{ @@ -124,7 +127,7 @@ func (s *zincTweetSearchServant) queryByTag(user *model.User, q *core.QueryReq, return s.postsFrom(resp) } -func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) (*core.QueryResp, error) { +func (s *zincTweetSearchServant) queryAny(user *core.User, offset, limit int) (*core.QueryResp, error) { queryMap := map[string]any{ "query": map[string]any{ "match_all": map[string]string{}, @@ -141,9 +144,9 @@ func (s *zincTweetSearchServant) queryAny(user *model.User, offset, limit int) ( } func (s *zincTweetSearchServant) postsFrom(resp *zinc.QueryResultT) (*core.QueryResp, error) { - posts := make([]*model.PostFormated, 0, len(resp.Hits.Hits)) + posts := make([]*core.PostFormated, 0, len(resp.Hits.Hits)) for _, hit := range resp.Hits.Hits { - item := &model.PostFormated{} + item := &core.PostFormated{} raw, err := json.Marshal(hit.Source) if err != nil { return nil, err diff --git a/internal/dao/security/attachment.go b/internal/dao/security/attachment.go index 3bd79461..706621ac 100644 --- a/internal/dao/security/attachment.go +++ b/internal/dao/security/attachment.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package security import ( diff --git a/internal/dao/slonik/slonik.go b/internal/dao/slonik/slonik.go index 8cfb49c3..bb8f82ad 100644 --- a/internal/dao/slonik/slonik.go +++ b/internal/dao/slonik/slonik.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + // Core service implement base sqlx+postgresql. All sub-service // will declare here and provide initial function. diff --git a/internal/dao/storage/alioss.go b/internal/dao/storage/alioss.go index 3519cba5..e72fa44c 100644 --- a/internal/dao/storage/alioss.go +++ b/internal/dao/storage/alioss.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/cos.go b/internal/dao/storage/cos.go index f7a7ebad..3c2ea65f 100644 --- a/internal/dao/storage/cos.go +++ b/internal/dao/storage/cos.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/huaweiobs.go b/internal/dao/storage/huaweiobs.go index 31656e6c..7db9818b 100644 --- a/internal/dao/storage/huaweiobs.go +++ b/internal/dao/storage/huaweiobs.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/localoss.go b/internal/dao/storage/localoss.go index f2ba55ab..584fea91 100644 --- a/internal/dao/storage/localoss.go +++ b/internal/dao/storage/localoss.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/minio.go b/internal/dao/storage/minio.go index b4da9fed..3859a5b7 100644 --- a/internal/dao/storage/minio.go +++ b/internal/dao/storage/minio.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/dao/storage/storage.go b/internal/dao/storage/storage.go index 8e124047..fff9d13f 100644 --- a/internal/dao/storage/storage.go +++ b/internal/dao/storage/storage.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package storage import ( diff --git a/internal/internal.go b/internal/internal.go index 8d51c97a..a8c0934f 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package internal import ( "github.com/rocboss/paopao-ce/internal/migration" - "github.com/rocboss/paopao-ce/internal/routers/api" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" + "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" ) func Initialize() { @@ -11,6 +15,6 @@ func Initialize() { migration.Run() // initialize service - service.Initialize() + broker.Initialize() api.Initialize() } diff --git a/internal/migration/migration.go b/internal/migration/migration.go index 44c16fb4..7437e996 100644 --- a/internal/migration/migration.go +++ b/internal/migration/migration.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !migration // +build !migration diff --git a/internal/migration/migration_embed.go b/internal/migration/migration_embed.go index 84952538..976b4f26 100644 --- a/internal/migration/migration_embed.go +++ b/internal/migration/migration_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build migration // +build migration diff --git a/internal/mirc/README.md b/internal/mirc/README.md new file mode 100644 index 00000000..5b2162a2 --- /dev/null +++ b/internal/mirc/README.md @@ -0,0 +1 @@ +### RESTful API for paopao-ce use [go-mir](https://github.com/alimy/mir) to generate service interface code automatic. diff --git a/internal/mirc/auto/api/v1/web_core.go b/internal/mirc/auto/api/v1/web_core.go new file mode 100644 index 00000000..5887e010 --- /dev/null +++ b/internal/mirc/auto/api/v1/web_core.go @@ -0,0 +1,159 @@ +// Code generated by go-mir. DO NOT EDIT. + +package v1 + +import ( + "net/http" + + "github.com/alimy/mir/v3" + gin "github.com/gin-gonic/gin" +) + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type WebCore interface { + // Chain provide handlers chain for gin + Chain() gin.HandlersChain + + Logout(c *gin.Context) mir.Error + Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) + Articles(c *gin.Context) mir.Error + Index(c *gin.Context) mir.Error + + mustEmbedUnimplementedWebCoreServant() +} + +type WebCoreBinding interface { + BindLogin(c *gin.Context) (*LoginReq, mir.Error) + + mustEmbedUnimplementedWebCoreBinding() +} + +type WebCoreRender interface { + RenderLogout(c *gin.Context, err mir.Error) + RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) + RenderArticles(c *gin.Context, err mir.Error) + RenderIndex(c *gin.Context, err mir.Error) + + mustEmbedUnimplementedWebCoreRender() +} + +// RegisterWebCoreServant register WebCore servant to gin +func RegisterWebCoreServant(e *gin.Engine, s WebCore, b WebCoreBinding, r WebCoreRender) { + router := e.Group("v1") + // use chain for router + middlewares := s.Chain() + router.Use(middlewares...) + + // register routes info to router + router.Handle("POST", "/user/logout/", func(c *gin.Context) { + r.RenderLogout(c, s.Logout(c)) + }) + + router.Handle("POST", "/user/login/", func(c *gin.Context) { + req, err := b.BindLogin(c) + if err != nil { + r.RenderLogin(c, nil, err) + } + resp, err := s.Login(c, req) + r.RenderLogin(c, resp, err) + }) + + { + h := func(c *gin.Context) { + r.RenderArticles(c, s.Articles(c)) + } + router.Handle("HEAD", "/articles/:category/", h) + router.Handle("GET", "/articles/:category/", h) + } + + router.Handle("GET", "/index/", func(c *gin.Context) { + r.RenderIndex(c, s.Index(c)) + }) + +} + +// UnimplementedWebCoreServant can be embedded to have forward compatible implementations. +type UnimplementedWebCoreServant struct { +} + +func (UnimplementedWebCoreServant) Chain() gin.HandlersChain { + return nil +} + +func (UnimplementedWebCoreServant) Logout(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedWebCoreServant) Login(c *gin.Context, req *LoginReq) (*LoginResp, mir.Error) { + return nil, mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedWebCoreServant) Articles(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedWebCoreServant) Index(c *gin.Context) mir.Error { + return mir.Errorln(http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented)) +} + +func (UnimplementedWebCoreServant) mustEmbedUnimplementedWebCoreServant() {} + +// UnimplementedWebCoreRender can be embedded to have forward compatible implementations. +type UnimplementedWebCoreRender struct { + RenderAny func(*gin.Context, any, mir.Error) +} + +func (r *UnimplementedWebCoreRender) RenderLogout(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedWebCoreRender) RenderLogin(c *gin.Context, data *LoginResp, err mir.Error) { + r.RenderAny(c, data, err) +} + +func (r *UnimplementedWebCoreRender) RenderArticles(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedWebCoreRender) RenderIndex(c *gin.Context, err mir.Error) { + r.RenderAny(c, nil, err) +} + +func (r *UnimplementedWebCoreRender) mustEmbedUnimplementedWebCoreRender() {} + +// UnimplementedWebCoreBinding can be embedded to have forward compatible implementations. +type UnimplementedWebCoreBinding struct { + BindAny func(*gin.Context, any) mir.Error +} + +func (b *UnimplementedWebCoreBinding) BindLogin(c *gin.Context) (*LoginReq, mir.Error) { + obj := new(LoginReq) + err := b.BindAny(c, obj) + return obj, err +} + +func (b *UnimplementedWebCoreBinding) mustEmbedUnimplementedWebCoreBinding() {} diff --git a/internal/mirc/main.go b/internal/mirc/main.go new file mode 100644 index 00000000..bf45791f --- /dev/null +++ b/internal/mirc/main.go @@ -0,0 +1,28 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package main + +import ( + "log" + + . "github.com/alimy/mir/v3/core" + . "github.com/alimy/mir/v3/engine" + + _ "github.com/rocboss/paopao-ce/internal/mirc/routes/v1" +) + +//go:generate go run main.go +func main() { + log.Println("generate code start") + opts := Options{ + RunMode(InSerialDebugMode), + GeneratorName(GeneratorGin), + SinkPath("auto"), + } + if err := Generate(opts); err != nil { + log.Fatal(err) + } + log.Println("generate code finish") +} diff --git a/internal/mirc/routes/README.md b/internal/mirc/routes/README.md new file mode 100644 index 00000000..0d7ac0c1 --- /dev/null +++ b/internal/mirc/routes/README.md @@ -0,0 +1 @@ +### RESTful API for paopao-ce diff --git a/internal/mirc/routes/v1/localoss.go b/internal/mirc/routes/v1/localoss.go new file mode 100644 index 00000000..bf2d09d8 --- /dev/null +++ b/internal/mirc/routes/v1/localoss.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(LocalOSS)) +} + +type LocalOSS struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_admin.go b/internal/mirc/routes/v1/web_admin.go new file mode 100644 index 00000000..db95fc86 --- /dev/null +++ b/internal/mirc/routes/v1/web_admin.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebAdmin)) +} + +type WebAdmin struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_alipay.go b/internal/mirc/routes/v1/web_alipay.go new file mode 100644 index 00000000..61de0906 --- /dev/null +++ b/internal/mirc/routes/v1/web_alipay.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebAlipay)) +} + +type WebAlipay struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_core.go b/internal/mirc/routes/v1/web_core.go new file mode 100644 index 00000000..83193986 --- /dev/null +++ b/internal/mirc/routes/v1/web_core.go @@ -0,0 +1,44 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebCore)) +} + +type AgentInfo struct { + Platform string `json:"platform"` + UserAgent string `json:"user_agent"` +} + +type ServerInfo struct { + ApiVer string `json:"api_ver"` +} + +type UserInfo struct { + Name string `json:"name"` +} + +type LoginReq struct { + AgentInfo AgentInfo `json:"agent_info"` + Name string `json:"name"` + Passwd string `json:"passwd"` +} + +type LoginResp struct { + UserInfo + ServerInfo ServerInfo `json:"server_info"` + JwtToken string `json:"jwt_token"` +} + +type WebCore struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` + Index func(Get) `mir:"/index/"` + Articles func(Get, Head) `mir:"/articles/:category/"` + Login func(Post, LoginReq) LoginResp `mir:"/user/login/"` + Logout func(Post) `mir:"/user/logout/"` +} diff --git a/internal/mirc/routes/v1/web_followship.go b/internal/mirc/routes/v1/web_followship.go new file mode 100644 index 00000000..1dd9de82 --- /dev/null +++ b/internal/mirc/routes/v1/web_followship.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebFollowship)) +} + +type WebFollowship struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_friendship.go b/internal/mirc/routes/v1/web_friendship.go new file mode 100644 index 00000000..e1276e99 --- /dev/null +++ b/internal/mirc/routes/v1/web_friendship.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebFriendship)) +} + +type WebFriendship struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_loose.go b/internal/mirc/routes/v1/web_loose.go new file mode 100644 index 00000000..7eff7d44 --- /dev/null +++ b/internal/mirc/routes/v1/web_loose.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebLoose)) +} + +type WebLoose struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_priv.go b/internal/mirc/routes/v1/web_priv.go new file mode 100644 index 00000000..3d73eb1b --- /dev/null +++ b/internal/mirc/routes/v1/web_priv.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebPriv)) +} + +type WebPriv struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/mirc/routes/v1/web_pub.go b/internal/mirc/routes/v1/web_pub.go new file mode 100644 index 00000000..7bfe2e3a --- /dev/null +++ b/internal/mirc/routes/v1/web_pub.go @@ -0,0 +1,15 @@ +package v1 + +import ( + . "github.com/alimy/mir/v3" + . "github.com/alimy/mir/v3/engine" +) + +func init() { + AddEntry(new(WebPub)) +} + +type WebPub struct { + Chain Chain `mir:"-"` + Group Group `mir:"v1"` +} diff --git a/internal/model/rest/contacts.go b/internal/model/rest/contacts.go deleted file mode 100644 index bbf31e42..00000000 --- a/internal/model/rest/contacts.go +++ /dev/null @@ -1,31 +0,0 @@ -package rest - -type RequestingFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` - Greetings string `json:"greetings" binding:"required"` -} - -type AddFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` -} - -type RejectFriendReq struct { - UserId int64 `json:"user_id" binding:"required"` -} - -type DeleteFriendReq struct { - UserId int64 `json:"user_id"` -} - -type ContactItem struct { - UserId int64 `json:"user_id"` - UserName string `json:"username"` - Nickname string `json:"nickname"` - Avatar string `json:"avatar"` - Phone string `json:"phone"` -} - -type ContactsResp struct { - Contacts []ContactItem `json:"contacts"` - Total int64 `json:"total"` -} diff --git a/internal/model/rest/tweets.go b/internal/model/rest/tweets.go deleted file mode 100644 index de85e179..00000000 --- a/internal/model/rest/tweets.go +++ /dev/null @@ -1,8 +0,0 @@ -package rest - -import "github.com/rocboss/paopao-ce/internal/model" - -type IndexTweetsResp struct { - Tweets []*model.PostFormated - Total int64 -} diff --git a/internal/model/rest/user.go b/internal/model/rest/user.go deleted file mode 100644 index 60ff467d..00000000 --- a/internal/model/rest/user.go +++ /dev/null @@ -1,11 +0,0 @@ -package rest - -type UserProfileResp struct { - ID int64 `json:"id"` - Nickname string `json:"nickname"` - Username string `json:"username"` - Status int `json:"status"` - Avatar string `json:"avatar"` - IsAdmin bool `json:"is_admin"` - IsFriend bool `json:"is_friend"` -} diff --git a/internal/proto/RADME.md b/internal/proto/RADME.md new file mode 100644 index 00000000..05d78ece --- /dev/null +++ b/internal/proto/RADME.md @@ -0,0 +1,2 @@ +### gRPC API +This directory contain some gRPC API define files. diff --git a/internal/proto/gen.go b/internal/proto/gen.go new file mode 100644 index 00000000..adb9c8db --- /dev/null +++ b/internal/proto/gen.go @@ -0,0 +1,5 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package proto diff --git a/internal/proto/tweets.proto b/internal/proto/tweets.proto new file mode 100644 index 00000000..1fcc9364 --- /dev/null +++ b/internal/proto/tweets.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package paopao; + +option go_package = "proto"; + +message Tag { + string name = 1; + int32 type = 2; +} diff --git a/internal/servants/base/base.go b/internal/servants/base/base.go new file mode 100644 index 00000000..6c204e7e --- /dev/null +++ b/internal/servants/base/base.go @@ -0,0 +1,77 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package base + +import ( + "net/http" + "os" + + "github.com/alimy/mir/v3" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/pkg/xerror" +) + +type BaseServant struct { + // TODO +} + +type BaseBinding struct { + // TODO +} + +type BaseRender struct { + // TODO +} + +func (BaseServant) userFrom(c *gin.Context) (*core.User, bool) { + if u, exists := c.Get("USER"); exists { + user, ok := u.(*core.User) + return user, ok + } + return nil, false +} + +func BindAny(c *gin.Context, obj any) mir.Error { + var errs xerror.ValidErrors + err := c.ShouldBind(obj) + if err != nil { + return mir.NewError(xerror.InvalidParams.Code(), xerror.InvalidParams.WithDetails(errs.Error())) + } + return nil +} + +func RenderAny(c *gin.Context, data any, err mir.Error) { + if err == nil { + hostname, _ := os.Hostname() + if data == nil { + data = gin.H{ + "code": 0, + "msg": "success", + "tracehost": hostname, + } + } else { + data = gin.H{ + "code": 0, + "msg": "success", + "data": data, + "tracehost": hostname, + } + } + c.JSON(http.StatusOK, data) + } else { + // TODO: error process logic + resp := gin.H{"code": err.StatusCode(), "msg": err.Error()} + // xerr := &xerror.Error{} + // if errors.As(err, xerr) { + // resp["code"], resp["msg"] = xerr.Code(), xerr.Msg() + // details := xerr.Details() + // if len(details) > 0 { + // resp["details"] = details + // } + // } + c.JSON(http.StatusInternalServerError, resp) + } +} diff --git a/internal/middleware/admin.go b/internal/servants/chain/admin.go similarity index 53% rename from internal/middleware/admin.go rename to internal/servants/chain/admin.go index f81b00ee..35a0fbc3 100644 --- a/internal/middleware/admin.go +++ b/internal/servants/chain/admin.go @@ -1,8 +1,12 @@ -package middleware +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package chain import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -10,8 +14,8 @@ import ( func Admin() gin.HandlerFunc { return func(c *gin.Context) { if user, exist := c.Get("USER"); exist { - if userModel, ok := user.(*model.User); ok { - if userModel.Status == model.UserStatusNormal && userModel.IsAdmin { + if userModel, ok := user.(*core.User); ok { + if userModel.Status == core.UserStatusNormal && userModel.IsAdmin { c.Next() return } diff --git a/internal/middleware/jwt.go b/internal/servants/chain/jwt.go similarity index 89% rename from internal/middleware/jwt.go rename to internal/servants/chain/jwt.go index 3fab7679..a0396630 100644 --- a/internal/middleware/jwt.go +++ b/internal/servants/chain/jwt.go @@ -1,4 +1,8 @@ -package middleware +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package chain import ( "strings" @@ -6,7 +10,7 @@ import ( "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v4" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -51,8 +55,8 @@ func JWT() gin.HandlerFunc { c.Set("USERNAME", claims.Username) // 加载用户信息 - user := &model.User{ - Model: &model.Model{ + user := &core.User{ + Model: &core.Model{ ID: claims.UID, }, } @@ -97,8 +101,8 @@ func JwtLoose() gin.HandlerFunc { c.Set("UID", claims.UID) c.Set("USERNAME", claims.Username) // 加载用户信息 - user := &model.User{ - Model: &model.Model{ + user := &core.User{ + Model: &core.Model{ ID: claims.UID, }, } diff --git a/internal/middleware/priv.go b/internal/servants/chain/priv.go similarity index 69% rename from internal/middleware/priv.go rename to internal/servants/chain/priv.go index fe31b008..f03c14b7 100644 --- a/internal/middleware/priv.go +++ b/internal/servants/chain/priv.go @@ -1,8 +1,12 @@ -package middleware +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package chain import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -12,8 +16,8 @@ func Priv() gin.HandlerFunc { if cfg.If("PhoneBind") { return func(c *gin.Context) { if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok { - if user.Status == model.UserStatusNormal { + if user, ok := u.(*core.User); ok { + if user.Status == core.UserStatusNormal { if user.Phone == "" { response := app.NewResponse(c) response.ToErrorResponse(errcode.AccountNoPhoneBind) @@ -32,7 +36,7 @@ func Priv() gin.HandlerFunc { } else { return func(c *gin.Context) { if u, exist := c.Get("USER"); exist { - if user, ok := u.(*model.User); ok && user.Status == model.UserStatusNormal { + if user, ok := u.(*core.User); ok && user.Status == core.UserStatusNormal { c.Next() return } diff --git a/internal/servants/docs/docs.go b/internal/servants/docs/docs.go new file mode 100644 index 00000000..7b6c9d36 --- /dev/null +++ b/internal/servants/docs/docs.go @@ -0,0 +1,17 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !docs +// +build !docs + +package docs + +import ( + "github.com/gin-gonic/gin" +) + +// RegisterDocs stub function for register docs asset route +func RegisterDocs(e *gin.Engine) { + // empty +} diff --git a/internal/servants/docs/docs_embed.go b/internal/servants/docs/docs_embed.go new file mode 100644 index 00000000..653e1c07 --- /dev/null +++ b/internal/servants/docs/docs_embed.go @@ -0,0 +1,21 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build docs +// +build docs + +package docs + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/docs/openapi" + "github.com/rocboss/paopao-ce/pkg/cfg" +) + +// RegisterDocs register docs asset route +func RegisterDocs(e *gin.Engine) { + cfg.Be("Docs:OpenAPI", func() { + e.StaticFS("/docs/openapi", openapi.NewFileSystem()) + }) +} diff --git a/internal/servants/localoss/localoss.go b/internal/servants/localoss/localoss.go new file mode 100644 index 00000000..828b3be2 --- /dev/null +++ b/internal/servants/localoss/localoss.go @@ -0,0 +1,28 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package localoss + +import ( + "path/filepath" + + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/sirupsen/logrus" +) + +type localossSrv struct { + // TODO +} + +// RouteLocalOSS register LocalOSS route if needed +func RouteLocalOSS(e *gin.Engine) { + savePath, err := filepath.Abs(conf.LocalOSSSetting.SavePath) + if err != nil { + logrus.Fatalf("get localOSS save path err: %v", err) + } + e.Static("/oss", savePath) + + logrus.Infof("register LocalOSS route in /oss on save path: %s", savePath) +} diff --git a/internal/servants/localoss/xerror.go b/internal/servants/localoss/xerror.go new file mode 100644 index 00000000..38132d24 --- /dev/null +++ b/internal/servants/localoss/xerror.go @@ -0,0 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package localoss + +import ( + "github.com/rocboss/paopao-ce/pkg/xerror" +) + +var ( + errFileUploadFailed = xerror.NewError(10200, "文件上传失败") + errFileInvalidExt = xerror.NewError(10201, "文件类型不合法") + errFileInvalidSize = xerror.NewError(10202, "文件大小超限") +) diff --git a/internal/servants/servants.go b/internal/servants/servants.go new file mode 100644 index 00000000..9ae3d0a7 --- /dev/null +++ b/internal/servants/servants.go @@ -0,0 +1,26 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package servants + +import ( + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/servants/docs" + "github.com/rocboss/paopao-ce/internal/servants/localoss" + "github.com/rocboss/paopao-ce/internal/servants/statick" + "github.com/rocboss/paopao-ce/internal/servants/web" + "github.com/rocboss/paopao-ce/pkg/cfg" +) + +// RegisterWebServants register all the servants to gin.Engine +func RegisterWebServants(e *gin.Engine) { + docs.RegisterDocs(e) + statick.RegisterStatick(e) + + cfg.Be("LocalOSS", func() { + localoss.RouteLocalOSS(e) + }) + + web.RouteWeb(e) +} diff --git a/internal/servants/statick/statick.go b/internal/servants/statick/statick.go new file mode 100644 index 00000000..d4c2bfdc --- /dev/null +++ b/internal/servants/statick/statick.go @@ -0,0 +1,17 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build !embed +// +build !embed + +package statick + +import ( + "github.com/gin-gonic/gin" +) + +// RegisterStatick stub function for register static asset route +func RegisterStatick(e *gin.Engine) { + // empty +} diff --git a/internal/servants/statick/statick_embed.go b/internal/servants/statick/statick_embed.go new file mode 100644 index 00000000..32da717f --- /dev/null +++ b/internal/servants/statick/statick_embed.go @@ -0,0 +1,31 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +//go:build embed +// +build embed + +package statick + +import ( + "net/http" + + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/web" +) + +// RegisterStatick register static assets route +func RegisterStatick(e *gin.Engine) { + routeStatic(e, "/", "/index.html", "/favicon.ico", "/assets/*filepath") +} + +func routeStatic(e *gin.Engine, paths ...string) { + staticHandler := http.FileServer(web.NewFileSystem()) + handler := func(c *gin.Context) { + staticHandler.ServeHTTP(c.Writer, c.Request) + } + for _, path := range paths { + e.GET(path, handler) + e.HEAD(path, handler) + } +} diff --git a/internal/servants/web/admin.go b/internal/servants/web/admin.go new file mode 100644 index 00000000..e4f2ef6e --- /dev/null +++ b/internal/servants/web/admin.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webAdminSrv struct { + // TODO +} diff --git a/internal/servants/web/alipay.go b/internal/servants/web/alipay.go new file mode 100644 index 00000000..80cfd7b7 --- /dev/null +++ b/internal/servants/web/alipay.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webAlipaySrv struct { + // TODO +} diff --git a/internal/servants/web/broker/attachment.go b/internal/servants/web/broker/attachment.go new file mode 100644 index 00000000..e8c69447 --- /dev/null +++ b/internal/servants/web/broker/attachment.go @@ -0,0 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker + +import ( + "github.com/rocboss/paopao-ce/internal/core" +) + +func CreateAttachment(attachment *core.Attachment) (*core.Attachment, error) { + return ds.CreateAttachment(attachment) +} diff --git a/internal/service/avatar.go b/internal/servants/web/broker/avatar.go similarity index 95% rename from internal/service/avatar.go rename to internal/servants/web/broker/avatar.go index 3ac302e0..04e183f4 100644 --- a/internal/service/avatar.go +++ b/internal/servants/web/broker/avatar.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "math/rand" diff --git a/internal/servants/web/broker/broker.go b/internal/servants/web/broker/broker.go new file mode 100644 index 00000000..79423901 --- /dev/null +++ b/internal/servants/web/broker/broker.go @@ -0,0 +1,48 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker + +import ( + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/dao" + "github.com/rocboss/paopao-ce/pkg/cfg" + "github.com/sirupsen/logrus" +) + +var ( + ds core.DataService + ts core.TweetSearchService + oss core.ObjectStorageService + DisablePhoneVerify bool +) + +func Initialize() { + ds = dao.DataService() + ts = dao.TweetSearchService() + oss = dao.ObjectStorageService() + DisablePhoneVerify = !cfg.If("Sms") +} + +// persistMediaContents 获取媒体内容并持久化 +func persistMediaContents(contents []*PostContentItem) (items []string, err error) { + items = make([]string, 0, len(contents)) + for _, item := range contents { + switch item.Type { + case core.ContentTypeImage, + core.ContentTypeVideo, + core.ContentTypeAudio, + core.ContentTypeAttachment, + core.ContentTypeChargeAttachment: + items = append(items, item.Content) + if err != nil { + continue + } + if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil { + logrus.Errorf("service.persistMediaContents failed: %s", err) + } + } + } + return +} diff --git a/internal/service/comment.go b/internal/servants/web/broker/comment.go similarity index 83% rename from internal/service/comment.go rename to internal/servants/web/broker/comment.go index f5165d71..7f9389dc 100644 --- a/internal/service/comment.go +++ b/internal/servants/web/broker/comment.go @@ -1,11 +1,15 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( + "github.com/rocboss/paopao-ce/internal/core" "time" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" ) @@ -28,8 +32,8 @@ type ReplyDelReq struct { ID int64 `json:"id" binding:"required"` } -func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.CommentFormated, int64, error) { - conditions := &model.ConditionsT{ +func GetPostComments(postID int64, sort string, offset, limit int) ([]*core.CommentFormated, int64, error) { + conditions := &core.ConditionsT{ "post_id": postID, "ORDER": sort, } @@ -61,7 +65,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com return nil, 0, err } - commentsFormated := []*model.CommentFormated{} + commentsFormated := []*core.CommentFormated{} for _, comment := range comments { commentFormated := comment.Format() for _, content := range contents { @@ -89,7 +93,7 @@ func GetPostComments(postID int64, sort string, offset, limit int) ([]*model.Com return commentsFormated, totalRows, nil } -func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *model.Comment, err error) { +func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) (comment *core.Comment, err error) { var mediaContents []string defer func() { @@ -113,7 +117,7 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) return nil, errcode.MaxCommentCount } ip := ctx.ClientIP() - comment = &model.Comment{ + comment = &core.Comment{ PostID: post.ID, UserID: userID, IP: ip, @@ -126,13 +130,13 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) for _, item := range param.Contents { // 检查附件是否是本站资源 - if item.Type == model.CONTENT_TYPE_IMAGE || item.Type == model.CONTENT_TYPE_VIDEO || item.Type == model.CONTENT_TYPE_ATTACHMENT { + if item.Type == core.ContentTypeImage || item.Type == core.ContentTypeVideo || item.Type == core.ContentTypeAttachment { if err := ds.CheckAttachment(item.Content); err != nil { continue } } - postContent := &model.CommentContent{ + postContent := &core.CommentContent{ CommentID: comment.ID, UserID: userID, Content: item.Content, @@ -153,10 +157,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) // 创建用户消息提醒 postMaster, err := ds.GetUserByID(post.UserID) if err == nil && postMaster.ID != userID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: postMaster.ID, - Type: model.MsgtypeComment, + Type: core.MsgtypeComment, Brief: "在泡泡中评论了你", PostID: post.ID, CommentID: comment.ID, @@ -169,10 +173,10 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) } // 创建消息提醒 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgtypeComment, + Type: core.MsgtypeComment, Brief: "在泡泡评论中@了你", PostID: post.ID, CommentID: comment.ID, @@ -182,11 +186,11 @@ func CreatePostComment(ctx *gin.Context, userID int64, param CommentCreationReq) return comment, nil } -func GetPostComment(id int64) (*model.Comment, error) { +func GetPostComment(id int64) (*core.Comment, error) { return ds.GetCommentByID(id) } -func DeletePostComment(comment *model.Comment) error { +func DeletePostComment(comment *core.Comment) error { // 加载post post, err := ds.GetPostByID(comment.PostID) if err == nil { @@ -198,7 +202,7 @@ func DeletePostComment(comment *model.Comment) error { return ds.DeleteComment(comment) } -func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, *model.Comment, int64, +func createPostPreHandler(commentID int64, userID, atUserID int64) (*core.Post, *core.Comment, int64, error) { // 加载Comment comment, err := ds.GetCommentByID(commentID) @@ -231,10 +235,10 @@ func createPostPreHandler(commentID int64, userID, atUserID int64) (*model.Post, return post, comment, atUserID, nil } -func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*model.CommentReply, error) { +func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, userID, atUserID int64) (*core.CommentReply, error) { var ( - post *model.Post - comment *model.Comment + post *core.Post + comment *core.Comment err error ) if post, comment, atUserID, err = createPostPreHandler(commentID, userID, atUserID); err != nil { @@ -243,7 +247,7 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u // 创建评论 ip := ctx.ClientIP() - reply := &model.CommentReply{ + reply := &core.CommentReply{ CommentID: commentID, UserID: userID, Content: content, @@ -268,10 +272,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u // 创建用户消息提醒 commentMaster, err := ds.GetUserByID(comment.UserID) if err == nil && commentMaster.ID != userID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: commentMaster.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论下回复了你", PostID: post.ID, CommentID: comment.ID, @@ -280,10 +284,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u } postMaster, err := ds.GetUserByID(post.UserID) if err == nil && postMaster.ID != userID && commentMaster.ID != postMaster.ID { - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: postMaster.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论下发布了新回复", PostID: post.ID, CommentID: comment.ID, @@ -294,10 +298,10 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u user, err := ds.GetUserByID(atUserID) if err == nil && user.ID != userID && commentMaster.ID != user.ID && postMaster.ID != user.ID { // 创建消息提醒 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgTypeReply, + Type: core.MsgTypeReply, Brief: "在泡泡评论的回复中@了你", PostID: post.ID, CommentID: comment.ID, @@ -309,11 +313,11 @@ func CreatePostCommentReply(ctx *gin.Context, commentID int64, content string, u return reply, nil } -func GetPostCommentReply(id int64) (*model.CommentReply, error) { +func GetPostCommentReply(id int64) (*core.CommentReply, error) { return ds.GetCommentReplyByID(id) } -func DeletePostCommentReply(reply *model.CommentReply) error { +func DeletePostCommentReply(reply *core.CommentReply) error { err := ds.DeleteCommentReply(reply) if err != nil { return err diff --git a/internal/service/message.go b/internal/servants/web/broker/message.go similarity index 84% rename from internal/service/message.go rename to internal/servants/web/broker/message.go index a025a849..6e5dd1a1 100644 --- a/internal/service/message.go +++ b/internal/servants/web/broker/message.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" @@ -6,7 +10,7 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -23,7 +27,7 @@ type WhisperReq struct { } // CreateWhisper 创建私信 -func CreateWhisper(c *gin.Context, msg *model.Message) (*model.Message, error) { +func CreateWhisper(c *gin.Context, msg *core.Message) (*core.Message, error) { whisperKey := fmt.Sprintf("WhisperTimes:%d", msg.SenderUserID) // 今日频次限制 @@ -65,8 +69,8 @@ func ReadMessage(id, userID int64) error { return ds.ReadMessage(message) } -func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int64, error) { - conditions := &model.ConditionsT{ +func GetMessages(userID int64, offset, limit int) ([]*core.MessageFormated, int64, error) { + conditions := &core.ConditionsT{ "receiver_user_id": userID, "ORDER": "id DESC", } @@ -83,7 +87,7 @@ func GetMessages(userID int64, offset, limit int) ([]*model.MessageFormated, int } // 好友申请消息不需要获取其他信息 - if mf.Type == model.MsgTypeRequestingFriend { + if mf.Type == core.MsgTypeRequestingFriend { continue } diff --git a/internal/service/post.go b/internal/servants/web/broker/post.go similarity index 76% rename from internal/service/post.go rename to internal/servants/web/broker/post.go index c8bda6b8..9a73528b 100644 --- a/internal/service/post.go +++ b/internal/servants/web/broker/post.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "errors" @@ -10,8 +14,6 @@ import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" "github.com/sirupsen/logrus" @@ -23,7 +25,7 @@ const TagTypeHot TagType = "hot" const TagTypeNew TagType = "new" type PostListReq struct { - Conditions *model.ConditionsT + Conditions *core.ConditionsT Offset int Limit int } @@ -37,7 +39,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"` + Visibility core.PostVisibleT `json:"visibility"` } type PostDelReq struct { @@ -53,8 +55,8 @@ type PostStickReq struct { } type PostVisibilityReq struct { - ID int64 `json:"id" binding:"required"` - Visibility model.PostVisibleT `json:"visibility"` + ID int64 `json:"id" binding:"required"` + Visibility core.PostVisibleT `json:"visibility"` } type PostStarReq struct { @@ -66,27 +68,25 @@ type PostCollectionReq struct { } type PostContentItem struct { - Content string `json:"content" binding:"required"` - Type model.PostContentT `json:"type" binding:"required"` - Sort int64 `json:"sort" binding:"required"` + Content string `json:"content" binding:"required"` + Type core.PostContentT `json:"type" binding:"required"` + Sort int64 `json:"sort" binding:"required"` } // Check 检查PostContentItem属性 func (p *PostContentItem) Check() error { // 检查附件是否是本站资源 - if p.Type == model.CONTENT_TYPE_IMAGE || p.Type == model.CONTENT_TYPE_VIDEO || p.Type == model. - CONTENT_TYPE_ATTACHMENT { + if p.Type == core.ContentTypeImage || p.Type == core.ContentTypeVideo || p.Type == core.ContentTypeAttachment { if err := ds.CheckAttachment(p.Content); err != nil { return err } } // 检查链接是否合法 - if p.Type == model.CONTENT_TYPE_LINK { + if p.Type == core.ContentTypeLink { if strings.Index(p.Content, "http://") != 0 && strings.Index(p.Content, "https://") != 0 { return fmt.Errorf("链接不合法") } } - return nil } @@ -103,7 +103,7 @@ func tagsFrom(originTags []string) []string { // CreatePost 创建文章 // TODO: 推文+推文内容需要在一个事务中添加,后续优化 -func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.PostFormated, err error) { +func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *core.PostFormated, err error) { var mediaContents []string defer func() { @@ -118,7 +118,7 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P ip := c.ClientIP() tags := tagsFrom(param.Tags) - post := &model.Post{ + post := &core.Post{ UserID: userID, Tags: strings.Join(tags, ","), IP: ip, @@ -138,11 +138,11 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P continue } - if item.Type == model.CONTENT_TYPE_ATTACHMENT && param.AttachmentPrice > 0 { - item.Type = model.CONTENT_TYPE_CHARGE_ATTACHMENT + if item.Type == core.ContentTypeAttachment && param.AttachmentPrice > 0 { + item.Type = core.ContentTypeChargeAttachment } - postContent := &model.PostContent{ + postContent := &core.PostContent{ PostID: post.ID, UserID: userID, Content: item.Content, @@ -155,10 +155,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P } // 私密推文不创建标签与用户提醒 - if post.Visibility != model.PostVisitPrivate { + if post.Visibility != core.PostVisitPrivate { // 创建标签 for _, t := range tags { - tag := &model.Tag{ + tag := &core.Tag{ UserID: userID, Tag: t, } @@ -174,10 +174,10 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P // 创建消息提醒 // TODO: 优化消息提醒处理机制 - go ds.CreateMessage(&model.Message{ + go ds.CreateMessage(&core.Message{ SenderUserID: userID, ReceiverUserID: user.ID, - Type: model.MsgTypePost, + Type: core.MsgTypePost, Brief: "在新发布的泡泡动态中@了你", PostID: post.ID, }) @@ -187,14 +187,14 @@ func CreatePost(c *gin.Context, userID int64, param PostCreationReq) (_ *model.P // 推送Search PushPostToSearch(post) - formatedPosts, err := ds.RevampPosts([]*model.PostFormated{post.Format()}) + formatedPosts, err := ds.RevampPosts([]*core.PostFormated{post.Format()}) if err != nil { return nil, err } return formatedPosts[0], nil } -func DeletePost(user *model.User, id int64) *errcode.Error { +func DeletePost(user *core.User, id int64) *errcode.Error { if user == nil { return errcode.NoPermission } @@ -261,8 +261,8 @@ func StickPost(id int64) error { return nil } -func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT) *errcode.Error { - if visibility >= model.PostVisitInvalid { +func VisiblePost(user *core.User, postId int64, visibility core.PostVisibleT) *errcode.Error { + if visibility >= core.PostVisitInvalid { return errcode.InvalidParams } @@ -287,11 +287,11 @@ func VisiblePost(user *model.User, postId int64, visibility model.PostVisibleT) return nil } -func GetPostStar(postID, userID int64) (*model.PostStar, error) { +func GetPostStar(postID, userID int64) (*core.PostStar, error) { return ds.GetUserPostStar(postID, userID) } -func CreatePostStar(postID, userID int64) (*model.PostStar, error) { +func CreatePostStar(postID, userID int64) (*core.PostStar, error) { // 加载Post post, err := ds.GetPostByID(postID) if err != nil { @@ -299,7 +299,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return nil, errors.New("no permision") } @@ -318,7 +318,7 @@ func CreatePostStar(postID, userID int64) (*model.PostStar, error) { return star, nil } -func DeletePostStar(star *model.PostStar) error { +func DeletePostStar(star *core.PostStar) error { err := ds.DeletePostStar(star) if err != nil { return err @@ -330,7 +330,7 @@ func DeletePostStar(star *model.PostStar) error { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return errors.New("no permision") } @@ -344,11 +344,11 @@ func DeletePostStar(star *model.PostStar) error { return nil } -func GetPostCollection(postID, userID int64) (*model.PostCollection, error) { +func GetPostCollection(postID, userID int64) (*core.PostCollection, error) { return ds.GetUserPostCollection(postID, userID) } -func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { +func CreatePostCollection(postID, userID int64) (*core.PostCollection, error) { // 加载Post post, err := ds.GetPostByID(postID) if err != nil { @@ -356,7 +356,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return nil, errors.New("no permision") } @@ -375,7 +375,7 @@ func CreatePostCollection(postID, userID int64) (*model.PostCollection, error) { return collection, nil } -func DeletePostCollection(collection *model.PostCollection) error { +func DeletePostCollection(collection *core.PostCollection) error { err := ds.DeletePostCollection(collection) if err != nil { return err @@ -387,7 +387,7 @@ func DeletePostCollection(collection *model.PostCollection) error { } // 私密post不可操作 - if post.Visibility == model.PostVisitPrivate { + if post.Visibility == core.PostVisitPrivate { return errors.New("no permision") } @@ -401,7 +401,7 @@ func DeletePostCollection(collection *model.PostCollection) error { return nil } -func GetPost(id int64) (*model.PostFormated, error) { +func GetPost(id int64) (*core.PostFormated, error) { post, err := ds.GetPostByID(id) if err != nil { @@ -431,15 +431,15 @@ func GetPost(id int64) (*model.PostFormated, error) { return postFormated, nil } -func GetPostContentByID(id int64) (*model.PostContent, error) { +func GetPostContentByID(id int64) (*core.PostContent, error) { return ds.GetPostContentByID(id) } -func GetIndexPosts(user *model.User, offset int, limit int) (*rest.IndexTweetsResp, error) { +func GetIndexPosts(user *core.User, offset int, limit int) (*core.IndexTweetList, error) { return ds.IndexPosts(user, offset, limit) } -func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error) { +func GetPostList(req *PostListReq) ([]*core.Post, []*core.PostFormated, error) { posts, err := ds.GetPosts(req.Conditions, req.Offset, req.Limit) if err != nil { return nil, nil, err @@ -448,11 +448,11 @@ func GetPostList(req *PostListReq) ([]*model.Post, []*model.PostFormated, error) return posts, postFormated, err } -func GetPostCount(conditions *model.ConditionsT) (int64, error) { +func GetPostCount(conditions *core.ConditionsT) (int64, error) { return ds.GetPostCount(conditions) } -func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetPostListFromSearch(user *core.User, q *core.QueryReq, offset, limit int) ([]*core.PostFormated, int64, error) { resp, err := ts.Search(user, q, offset, limit) if err != nil { return nil, 0, err @@ -464,7 +464,7 @@ func GetPostListFromSearch(user *model.User, q *core.QueryReq, offset, limit int return posts, resp.Total, nil } -func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetPostListFromSearchByQuery(user *core.User, query string, offset, limit int) ([]*core.PostFormated, int64, error) { q := &core.QueryReq{ Query: query, Type: "search", @@ -472,9 +472,9 @@ func GetPostListFromSearchByQuery(user *model.User, query string, offset, limit return GetPostListFromSearch(user, q, offset, limit) } -func PushPostToSearch(post *model.Post) { +func PushPostToSearch(post *core.Post) { postFormated := post.Format() - postFormated.User = &model.UserFormated{ + postFormated.User = &core.UserFormated{ ID: post.UserID, } contents, _ := ds.GetPostContentsByIDs([]int64{post.ID}) @@ -484,7 +484,7 @@ func PushPostToSearch(post *model.Post) { contentFormated := "" for _, content := range postFormated.Contents { - if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE { + if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle { contentFormated = contentFormated + content.Content + "\n" } } @@ -496,7 +496,7 @@ func PushPostToSearch(post *model.Post) { ts.AddDocuments(docs, fmt.Sprintf("%d", post.ID)) } -func DeleteSearchPost(post *model.Post) error { +func DeleteSearchPost(post *core.Post) error { return ts.DeleteDocuments([]string{fmt.Sprintf("%d", post.ID)}) } @@ -505,8 +505,8 @@ func PushPostsToSearch(c *gin.Context) { defer conf.Redis.Del(c, "JOB_PUSH_TO_SEARCH") splitNum := 1000 - totalRows, _ := GetPostCount(&model.ConditionsT{ - "visibility IN ?": []model.PostVisibleT{model.PostVisitPublic, model.PostVisitFriend}, + totalRows, _ := GetPostCount(&core.ConditionsT{ + "visibility IN ?": []core.PostVisibleT{core.PostVisitPublic, core.PostVisitFriend}, }) pages := math.Ceil(float64(totalRows) / float64(splitNum)) @@ -514,7 +514,7 @@ func PushPostsToSearch(c *gin.Context) { for i := 0; i < nums; i++ { posts, postsFormated, err := GetPostList(&PostListReq{ - Conditions: &model.ConditionsT{}, + Conditions: &core.ConditionsT{}, Offset: i * splitNum, Limit: splitNum, }) @@ -524,7 +524,7 @@ func PushPostsToSearch(c *gin.Context) { for i, pf := range postsFormated { contentFormated := "" for _, content := range pf.Contents { - if content.Type == model.CONTENT_TYPE_TEXT || content.Type == model.CONTENT_TYPE_TITLE { + if content.Type == core.ContentTypeText || content.Type == core.ContentTypeTitle { contentFormated = contentFormated + content.Content + "\n" } } @@ -538,22 +538,22 @@ func PushPostsToSearch(c *gin.Context) { } } -func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) { +func GetPostTags(param *PostTagsReq) ([]*core.TagFormated, error) { num := param.Num if num > conf.AppSetting.MaxPageSize { num = conf.AppSetting.MaxPageSize } - conditions := &model.ConditionsT{} + conditions := &core.ConditionsT{} if param.Type == TagTypeHot { // 热门标签 - conditions = &model.ConditionsT{ + conditions = &core.ConditionsT{ "ORDER": "quote_num DESC", } } if param.Type == TagTypeNew { // 热门标签 - conditions = &model.ConditionsT{ + conditions = &core.ConditionsT{ "ORDER": "id DESC", } } @@ -571,7 +571,7 @@ func GetPostTags(param *PostTagsReq) ([]*model.TagFormated, error) { users, _ := ds.GetUsersByIDs(userIds) - tagsFormated := []*model.TagFormated{} + tagsFormated := []*core.TagFormated{} for _, tag := range tags { tagFormated := tag.Format() for _, user := range users { diff --git a/internal/service/sign.go b/internal/servants/web/broker/sign.go similarity index 79% rename from internal/service/sign.go rename to internal/servants/web/broker/sign.go index d3ec373a..c8883638 100644 --- a/internal/service/sign.go +++ b/internal/servants/web/broker/sign.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" diff --git a/internal/service/user.go b/internal/servants/web/broker/user.go similarity index 76% rename from internal/service/user.go rename to internal/servants/web/broker/user.go index 7289c067..66919a99 100644 --- a/internal/service/user.go +++ b/internal/servants/web/broker/user.go @@ -1,4 +1,8 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( "fmt" @@ -10,15 +14,14 @@ import ( "github.com/gin-gonic/gin" "github.com/gofrs/uuid" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" + "github.com/rocboss/paopao-ce/internal/core" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/rocboss/paopao-ce/pkg/util" "github.com/sirupsen/logrus" ) -const MAX_CAPTCHA_TIMES = 2 +const _MaxCaptchaTimes = 2 type PhoneCaptchaReq struct { Phone string `json:"phone" form:"phone" binding:"required"` @@ -59,19 +62,48 @@ type ChangeUserStatusReq struct { Status int `json:"status" form:"status" binding:"required"` } -const LOGIN_ERR_KEY = "PaoPaoUserLoginErr" -const MAX_LOGIN_ERR_TIMES = 10 +type RequestingFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` + Greetings string `json:"greetings" binding:"required"` +} + +type AddFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` +} + +type RejectFriendReq struct { + UserId int64 `json:"user_id" binding:"required"` +} + +type DeleteFriendReq struct { + UserId int64 `json:"user_id"` +} + +type UserProfileResp struct { + ID int64 `json:"id"` + Nickname string `json:"nickname"` + Username string `json:"username"` + Status int `json:"status"` + Avatar string `json:"avatar"` + IsAdmin bool `json:"is_admin"` + IsFriend bool `json:"is_friend"` +} + +const ( + _LoginErrKey = "PaoPaoUserLoginErr" + _MaxLoginErrTimes = 10 +) // DoLogin 用户认证 -func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) { +func DoLogin(ctx *gin.Context, param *AuthRequest) (*core.User, error) { user, err := ds.GetUserByUsername(param.Username) if err != nil { return nil, errcode.UnauthorizedAuthNotExist } if user.Model != nil && user.ID > 0 { - if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result(); err == nil { - if convert.StrTo(errTimes).MustInt() >= MAX_LOGIN_ERR_TIMES { + if errTimes, err := conf.Redis.Get(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result(); err == nil { + if convert.StrTo(errTimes).MustInt() >= _MaxLoginErrTimes { return nil, errcode.TooManyLoginError } } @@ -79,19 +111,19 @@ func DoLogin(ctx *gin.Context, param *AuthRequest) (*model.User, error) { // 对比密码是否正确 if ValidPassword(user.Password, param.Password, user.Salt) { - if user.Status == model.UserStatusClosed { + if user.Status == core.UserStatusClosed { return nil, errcode.UserHasBeenBanned } // 清空登录计数 - conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)) + conf.Redis.Del(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)) return user, nil } // 登录错误计数 - _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID)).Result() + _, err = conf.Redis.Incr(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID)).Result() if err == nil { - conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", LOGIN_ERR_KEY, user.ID), time.Hour).Result() + conf.Redis.Expire(ctx, fmt.Sprintf("%s:%d", _LoginErrKey, user.ID), time.Hour).Result() } return nil, errcode.UnauthorizedAuthFailed @@ -106,8 +138,8 @@ func ValidPassword(dbPassword, password, salt string) bool { } // CheckStatus 检测用户权限 -func CheckStatus(user *model.User) bool { - return user.Status == model.UserStatusNormal +func CheckStatus(user *core.User) bool { + return user.Status == core.UserStatusNormal } // ValidUsername 验证用户 @@ -161,7 +193,7 @@ func CheckPhoneCaptcha(phone, captcha string) *errcode.Error { return errcode.ErrorPhoneCaptcha } - if c.UseTimes >= MAX_CAPTCHA_TIMES { + if c.UseTimes >= _MaxCaptchaTimes { return errcode.MaxPhoneCaptchaUseTimes } @@ -198,16 +230,16 @@ func EncryptPasswordAndSalt(password string) (string, string) { } // Register 用户注册 -func Register(username, password string) (*model.User, error) { +func Register(username, password string) (*core.User, error) { password, salt := EncryptPasswordAndSalt(password) - user := &model.User{ + user := &core.User{ Nickname: username, Username: username, Password: password, Avatar: GetRandomAvatar(), Salt: salt, - Status: model.UserStatusNormal, + Status: core.UserStatusNormal, } user, err := ds.CreateUser(user) @@ -218,40 +250,40 @@ func Register(username, password string) (*model.User, error) { return user, nil } -func RequestingFriend(user *model.User, param *rest.RequestingFriendReq) error { +func RequestingFriend(user *core.User, param *RequestingFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.RequestingFriend(user.ID, param.UserId, param.Greetings) } -func AddFriend(user *model.User, param *rest.AddFriendReq) error { +func AddFriend(user *core.User, param *AddFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.AddFriend(user.ID, param.UserId) } -func RejectFriend(user *model.User, param *rest.RejectFriendReq) error { +func RejectFriend(user *core.User, param *RejectFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.RejectFriend(user.ID, param.UserId) } -func DeleteFriend(user *model.User, param *rest.DeleteFriendReq) error { +func DeleteFriend(user *core.User, param *DeleteFriendReq) error { if _, err := ds.GetUserByID(param.UserId); err != nil { return errcode.NotExistFriendId } return ds.DeleteFriend(user.ID, param.UserId) } -func GetContacts(user *model.User, offset int, limit int) (*rest.ContactsResp, error) { +func GetContacts(user *core.User, offset int, limit int) (*core.ContactList, error) { return ds.GetContacts(user.ID, offset, limit) } // GetUserInfo 获取用户信息 -func GetUserInfo(param *AuthRequest) (*model.User, error) { +func GetUserInfo(param *AuthRequest) (*core.User, error) { user, err := ds.GetUserByUsername(param.Username) if err != nil { @@ -265,7 +297,7 @@ func GetUserInfo(param *AuthRequest) (*model.User, error) { return nil, errcode.UnauthorizedAuthNotExist } -func GetUserByID(id int64) (*model.User, error) { +func GetUserByID(id int64) (*core.User, error) { user, err := ds.GetUserByID(id) if err != nil { @@ -279,15 +311,15 @@ func GetUserByID(id int64) (*model.User, error) { return nil, errcode.NoExistUsername } -func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp, error) { +func GetUserByUsername(user *core.User, username string) (*UserProfileResp, error) { other, err := ds.GetUserByUsername(username) if err != nil { return nil, err } - var resp *rest.UserProfileResp + var resp *UserProfileResp if other.Model != nil && other.ID > 0 { - resp = &rest.UserProfileResp{ + resp = &UserProfileResp{ ID: other.ID, Nickname: other.Nickname, Username: other.Username, @@ -307,14 +339,14 @@ func GetUserByUsername(user *model.User, username string) (*rest.UserProfileResp } // UpdateUserInfo 更新用户信息 -func UpdateUserInfo(user *model.User) *errcode.Error { +func UpdateUserInfo(user *core.User) *errcode.Error { if err := ds.UpdateUser(user); err != nil { return errcode.ServerError } return nil } -func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) { +func ChangeUserAvatar(user *core.User, avatar string) (err *errcode.Error) { defer func() { if err != nil { deleteOssObjects([]string{avatar}) @@ -336,7 +368,7 @@ func ChangeUserAvatar(user *model.User, avatar string) (err *errcode.Error) { } // GetUserCollections 获取用户收藏列表 -func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetUserCollections(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) { collections, err := ds.GetUserPostCollections(userID, offset, limit) if err != nil { return nil, 0, err @@ -345,7 +377,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, if err != nil { return nil, 0, err } - var posts []*model.Post + var posts []*core.Post for _, collection := range collections { posts = append(posts, collection.Post) } @@ -358,7 +390,7 @@ func GetUserCollections(userID int64, offset, limit int) ([]*model.PostFormated, } // GetUserStars 获取用户点赞列表 -func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64, error) { +func GetUserStars(userID int64, offset, limit int) ([]*core.PostFormated, int64, error) { stars, err := ds.GetUserPostStars(userID, offset, limit) if err != nil { return nil, 0, err @@ -368,7 +400,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64 return nil, 0, err } - var posts []*model.Post + var posts []*core.Post for _, star := range stars { posts = append(posts, star.Post) } @@ -381,7 +413,7 @@ func GetUserStars(userID int64, offset, limit int) ([]*model.PostFormated, int64 } // GetUserWalletBills 获取用户账单列表 -func GetUserWalletBills(userID int64, offset, limit int) ([]*model.WalletStatement, int64, error) { +func GetUserWalletBills(userID int64, offset, limit int) ([]*core.WalletStatement, int64, error) { bills, err := ds.GetUserWalletBills(userID, offset, limit) if err != nil { return nil, 0, err @@ -448,7 +480,7 @@ func IsFriend(userId, friendId int64) bool { } // checkPermision 检查是否拥有者或管理员 -func checkPermision(user *model.User, targetUserId int64) *errcode.Error { +func checkPermision(user *core.User, targetUserId int64) *errcode.Error { if user == nil || (user.ID != targetUserId && !user.IsAdmin) { return errcode.NoPermission } diff --git a/internal/service/wallet.go b/internal/servants/web/broker/wallet.go similarity index 69% rename from internal/service/wallet.go rename to internal/servants/web/broker/wallet.go index 0f22b23f..6f89edf8 100644 --- a/internal/service/wallet.go +++ b/internal/servants/web/broker/wallet.go @@ -1,11 +1,15 @@ -package service +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package broker import ( + "github.com/rocboss/paopao-ce/internal/core" "time" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" "github.com/rocboss/paopao-ce/pkg/errcode" ) @@ -13,11 +17,11 @@ type RechargeReq struct { Amount int64 `json:"amount" form:"amount" binding:"required"` } -func GetRechargeByID(id int64) (*model.WalletRecharge, error) { +func GetRechargeByID(id int64) (*core.WalletRecharge, error) { return ds.GetRechargeByID(id) } -func CreateRecharge(userID, amount int64) (*model.WalletRecharge, error) { +func CreateRecharge(userID, amount int64) (*core.WalletRecharge, error) { return ds.CreateRecharge(userID, amount) } @@ -44,7 +48,7 @@ func FinishRecharge(ctx *gin.Context, id int64, tradeNo string) error { return nil } -func BuyPostAttachment(post *model.Post, user *model.User) error { +func BuyPostAttachment(post *core.Post, user *core.User) error { if user.Balance < post.AttachmentPrice { return errcode.InsuffientDownloadMoney } diff --git a/internal/servants/web/core.go b/internal/servants/web/core.go new file mode 100644 index 00000000..085e5bcf --- /dev/null +++ b/internal/servants/web/core.go @@ -0,0 +1,51 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +import ( + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" + "github.com/rocboss/paopao-ce/internal/servants/base" +) + +var ( + _ api.WebCore = (*webCoreSrv)(nil) + _ api.WebCoreBinding = (*webCoreBinding)(nil) + _ api.WebCoreRender = (*webCoreRender)(nil) +) + +type webCoreSrv struct { + base.BaseServant + api.UnimplementedWebCoreServant +} + +type webCoreBinding struct { + base.BaseBinding + *api.UnimplementedWebCoreBinding +} + +type webCoreRender struct { + base.BaseRender + *api.UnimplementedWebCoreRender +} + +func newWebCoreSrv() api.WebCore { + return &webCoreSrv{} +} + +func newWebCoreBinding() api.WebCoreBinding { + return &webCoreBinding{ + UnimplementedWebCoreBinding: &api.UnimplementedWebCoreBinding{ + BindAny: base.BindAny, + }, + } +} + +func newWebCoreRender() api.WebCoreRender { + return &webCoreRender{ + UnimplementedWebCoreRender: &api.UnimplementedWebCoreRender{ + RenderAny: base.RenderAny, + }, + } +} diff --git a/internal/servants/web/followship.go b/internal/servants/web/followship.go new file mode 100644 index 00000000..4158de39 --- /dev/null +++ b/internal/servants/web/followship.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webFollowshipSrv struct { + // TODO +} diff --git a/internal/servants/web/friendship.go b/internal/servants/web/friendship.go new file mode 100644 index 00000000..a4fb3d59 --- /dev/null +++ b/internal/servants/web/friendship.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webFriendshipSrv struct { + // TODO +} diff --git a/internal/servants/web/loose.go b/internal/servants/web/loose.go new file mode 100644 index 00000000..51a309a1 --- /dev/null +++ b/internal/servants/web/loose.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webLooseSrv struct { + // TODO +} diff --git a/internal/servants/web/priv.go b/internal/servants/web/priv.go new file mode 100644 index 00000000..51f0f486 --- /dev/null +++ b/internal/servants/web/priv.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webPrivSrv struct { + // TODO +} diff --git a/internal/servants/web/pub.go b/internal/servants/web/pub.go new file mode 100644 index 00000000..d7c68ec5 --- /dev/null +++ b/internal/servants/web/pub.go @@ -0,0 +1,9 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +type webPubSrv struct { + // TODO +} diff --git a/internal/routers/api/api.go b/internal/servants/web/routers/api/api.go similarity index 89% rename from internal/routers/api/api.go rename to internal/servants/web/routers/api/api.go index c722ac88..39e748ab 100644 --- a/internal/routers/api/api.go +++ b/internal/servants/web/routers/api/api.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( diff --git a/internal/routers/api/assets/comic.ttf b/internal/servants/web/routers/api/assets/comic.ttf similarity index 100% rename from internal/routers/api/assets/comic.ttf rename to internal/servants/web/routers/api/assets/comic.ttf diff --git a/internal/routers/api/attachment.go b/internal/servants/web/routers/api/attachment.go similarity index 79% rename from internal/routers/api/attachment.go rename to internal/servants/web/routers/api/attachment.go index 905b2c03..143c0c12 100644 --- a/internal/routers/api/attachment.go +++ b/internal/servants/web/routers/api/attachment.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -6,19 +10,19 @@ import ( "github.com/disintegration/imaging" "github.com/gin-gonic/gin" "github.com/gofrs/uuid" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/sirupsen/logrus" ) -var uploadAttachmentTypeMap = map[string]model.AttachmentType{ - "public/image": model.ATTACHMENT_TYPE_IMAGE, - "public/avatar": model.ATTACHMENT_TYPE_IMAGE, - "public/video": model.ATTACHMENT_TYPE_VIDEO, - "attachment": model.ATTACHMENT_TYPE_OTHER, +var uploadAttachmentTypeMap = map[string]core.AttachmentType{ + "public/image": core.AttachmentTypeImage, + "public/avatar": core.AttachmentTypeImage, + "public/video": core.AttachmentTypeVideo, + "attachment": core.AttachmentTypeOther, } func GeneratePath(s string) string { @@ -110,7 +114,7 @@ func UploadAttachment(c *gin.Context) { } // 构造附件Model - attachment := &model.Attachment{ + attachment := &core.Attachment{ FileSize: fileHeader.Size, Content: objectUrl, } @@ -120,7 +124,7 @@ func UploadAttachment(c *gin.Context) { } attachment.Type = uploadAttachmentTypeMap[uploadType] - if attachment.Type == model.ATTACHMENT_TYPE_IMAGE { + if attachment.Type == core.AttachmentTypeImage { var src image.Image src, err = imaging.Decode(file) if err == nil { @@ -128,7 +132,7 @@ func UploadAttachment(c *gin.Context) { } } - attachment, err = service.CreateAttachment(attachment) + attachment, err = broker.CreateAttachment(attachment) if err != nil { logrus.Errorf("service.CreateAttachment err: %v", err) response.ToErrorResponse(errcode.FileUploadFailed) @@ -142,15 +146,15 @@ func DownloadAttachmentPrecheck(c *gin.Context) { contentID := convert.StrTo(c.Query("id")).MustInt64() // 加载content - content, err := service.GetPostContentByID(contentID) + content, err := broker.GetPostContentByID(contentID) if err != nil { logrus.Errorf("service.GetPostContentByID err: %v", err) response.ToErrorResponse(errcode.InvalidDownloadReq) } user, _ := c.Get("USER") - if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT { + if content.Type == core.ContentTypeChargeAttachment { // 加载post - post, err := service.GetPost(content.PostID) + post, err := broker.GetPost(content.PostID) if err != nil { logrus.Errorf("service.GetPost err: %v", err) response.ToResponse(gin.H{ @@ -160,7 +164,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) { } // 发布者或管理员免费下载 - if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin { + if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin { response.ToResponse(gin.H{ "paid": true, }) @@ -169,7 +173,7 @@ func DownloadAttachmentPrecheck(c *gin.Context) { // 检测是否有购买记录 response.ToResponse(gin.H{ - "paid": service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID), + "paid": broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID), }) return } @@ -184,18 +188,18 @@ func DownloadAttachment(c *gin.Context) { contentID := convert.StrTo(c.Query("id")).MustInt64() // 加载content - content, err := service.GetPostContentByID(contentID) + content, err := broker.GetPostContentByID(contentID) if err != nil { logrus.Errorf("service.GetPostContentByID err: %v", err) response.ToErrorResponse(errcode.InvalidDownloadReq) } // 收费附件 - if content.Type == model.CONTENT_TYPE_CHARGE_ATTACHMENT { + if content.Type == core.ContentTypeChargeAttachment { user, _ := c.Get("USER") // 加载post - post, err := service.GetPost(content.PostID) + post, err := broker.GetPost(content.PostID) if err != nil { logrus.Errorf("service.GetPost err: %v", err) response.ToResponse(gin.H{ @@ -207,24 +211,24 @@ func DownloadAttachment(c *gin.Context) { paidFlag := false // 发布者或管理员免费下载 - if post.UserID == user.(*model.User).ID || user.(*model.User).IsAdmin { + if post.UserID == user.(*core.User).ID || user.(*core.User).IsAdmin { paidFlag = true } // 检测是否有购买记录 - if service.CheckPostAttachmentIsPaid(post.ID, user.(*model.User).ID) { + if broker.CheckPostAttachmentIsPaid(post.ID, user.(*core.User).ID) { paidFlag = true } if !paidFlag { // 未购买,则尝试购买 - err := service.BuyPostAttachment(&model.Post{ - Model: &model.Model{ + err := broker.BuyPostAttachment(&core.Post{ + Model: &core.Model{ ID: post.ID, }, UserID: post.UserID, AttachmentPrice: post.AttachmentPrice, - }, user.(*model.User)) + }, user.(*core.User)) if err != nil { logrus.Errorf("service.BuyPostAttachment err: %v", err) if err == errcode.InsuffientDownloadMoney { diff --git a/internal/routers/api/comment.go b/internal/servants/web/routers/api/comment.go similarity index 75% rename from internal/routers/api/comment.go rename to internal/servants/web/routers/api/comment.go index 4b1fca36..0779eabb 100644 --- a/internal/routers/api/comment.go +++ b/internal/servants/web/routers/api/comment.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -14,7 +18,7 @@ func GetPostComments(c *gin.Context) { postID := convert.StrTo(c.Query("id")).MustInt64() response := app.NewResponse(c) - contents, totalRows, err := service.GetPostComments(postID, "id ASC", 0, 0) + contents, totalRows, err := broker.GetPostComments(postID, "id ASC", 0, 0) if err != nil { logrus.Errorf("service.GetPostComments err: %v\n", err) @@ -26,7 +30,7 @@ func GetPostComments(c *gin.Context) { } func CreatePostComment(c *gin.Context) { - param := service.CommentCreationReq{} + param := broker.CommentCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -36,7 +40,7 @@ func CreatePostComment(c *gin.Context) { } userID, _ := c.Get("UID") - comment, err := service.CreatePostComment(c, userID.(int64), param) + comment, err := broker.CreatePostComment(c, userID.(int64), param) if err != nil { if err == errcode.MaxCommentCount { @@ -52,7 +56,7 @@ func CreatePostComment(c *gin.Context) { } func DeletePostComment(c *gin.Context) { - param := service.CommentDelReq{} + param := broker.CommentDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -62,20 +66,20 @@ func DeletePostComment(c *gin.Context) { } user, _ := c.Get("USER") - comment, err := service.GetPostComment(param.ID) + comment, err := broker.GetPostComment(param.ID) if err != nil { logrus.Errorf("service.GetPostComment err: %v\n", err) response.ToErrorResponse(errcode.GetCommentFailed) return } - if user.(*model.User).ID != comment.UserID && !user.(*model.User).IsAdmin { + if user.(*core.User).ID != comment.UserID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } // 执行删除 - err = service.DeletePostComment(comment) + err = broker.DeletePostComment(comment) if err != nil { logrus.Errorf("service.DeletePostComment err: %v\n", err) response.ToErrorResponse(errcode.DeleteCommentFailed) @@ -86,7 +90,7 @@ func DeletePostComment(c *gin.Context) { } func CreatePostCommentReply(c *gin.Context) { - param := service.CommentReplyCreationReq{} + param := broker.CommentReplyCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -96,7 +100,7 @@ func CreatePostCommentReply(c *gin.Context) { } user, _ := c.Get("USER") - comment, err := service.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*model.User).ID, param.AtUserID) + comment, err := broker.CreatePostCommentReply(c, param.CommentID, param.Content, user.(*core.User).ID, param.AtUserID) if err != nil { logrus.Errorf("service.CreatePostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.CreateReplyFailed) @@ -107,7 +111,7 @@ func CreatePostCommentReply(c *gin.Context) { } func DeletePostCommentReply(c *gin.Context) { - param := service.ReplyDelReq{} + param := broker.ReplyDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -118,20 +122,20 @@ func DeletePostCommentReply(c *gin.Context) { user, _ := c.Get("USER") - reply, err := service.GetPostCommentReply(param.ID) + reply, err := broker.GetPostCommentReply(param.ID) if err != nil { logrus.Errorf("service.GetPostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.GetReplyFailed) return } - if user.(*model.User).ID != reply.UserID && !user.(*model.User).IsAdmin { + if user.(*core.User).ID != reply.UserID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } // 执行删除 - err = service.DeletePostCommentReply(reply) + err = broker.DeletePostCommentReply(reply) if err != nil { logrus.Errorf("service.DeletePostCommentReply err: %v\n", err) response.ToErrorResponse(errcode.DeleteCommentFailed) diff --git a/internal/routers/api/home.go b/internal/servants/web/routers/api/home.go similarity index 86% rename from internal/routers/api/home.go rename to internal/servants/web/routers/api/home.go index 80489978..b863b712 100644 --- a/internal/routers/api/home.go +++ b/internal/servants/web/routers/api/home.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -12,8 +16,8 @@ import ( "github.com/gin-gonic/gin" "github.com/gofrs/uuid" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/debug" @@ -39,8 +43,8 @@ func SyncSearchIndex(c *gin.Context) { user, _ := c.Get("USER") - if user.(*model.User).IsAdmin { - go service.PushPostsToSearch(c) + if user.(*core.User).IsAdmin { + go broker.PushPostsToSearch(c) } response.ToResponse(nil) @@ -74,7 +78,7 @@ func GetCaptcha(c *gin.Context) { } func PostCaptcha(c *gin.Context) { - param := service.PhoneCaptchaReq{} + param := broker.PhoneCaptchaReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -96,7 +100,7 @@ func PostCaptcha(c *gin.Context) { return } - err := service.SendPhoneCaptcha(c, param.Phone) + err := broker.SendPhoneCaptcha(c, param.Phone) if err != nil { logrus.Errorf("app.SendPhoneCaptcha errs: %v", errs) response.ToErrorResponse(errcode.GetPhoneCaptchaError) diff --git a/internal/routers/api/message.go b/internal/servants/web/routers/api/message.go similarity index 74% rename from internal/routers/api/message.go rename to internal/servants/web/routers/api/message.go index 8c24cbd2..9cc72ffd 100644 --- a/internal/routers/api/message.go +++ b/internal/servants/web/routers/api/message.go @@ -1,9 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/errcode" "github.com/sirupsen/logrus" @@ -12,12 +16,12 @@ import ( func GetUnreadMsgCount(c *gin.Context) { response := app.NewResponse(c) - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } - count, _ := service.GetUnreadCount(user.ID) + count, _ := broker.GetUnreadCount(user.ID) response.ToResponse(gin.H{ "count": count, @@ -28,7 +32,7 @@ func GetMessages(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - messages, totalRows, err := service.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + messages, totalRows, err := broker.GetMessages(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetMessages err: %v\n", err) @@ -40,7 +44,7 @@ func GetMessages(c *gin.Context) { } func ReadMessage(c *gin.Context) { - param := service.ReadMessageReq{} + param := broker.ReadMessageReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -50,7 +54,7 @@ func ReadMessage(c *gin.Context) { } userID, _ := c.Get("UID") - err := service.ReadMessage(param.ID, userID.(int64)) + err := broker.ReadMessage(param.ID, userID.(int64)) if err != nil { logrus.Errorf("service.ReadMessage err: %v\n", err) response.ToErrorResponse(errcode.ReadMessageFailed) @@ -61,7 +65,7 @@ func ReadMessage(c *gin.Context) { } func SendUserWhisper(c *gin.Context) { - param := service.WhisperReq{} + param := broker.WhisperReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -78,10 +82,10 @@ func SendUserWhisper(c *gin.Context) { return } - _, err := service.CreateWhisper(c, &model.Message{ + _, err := broker.CreateWhisper(c, &core.Message{ SenderUserID: userID.(int64), ReceiverUserID: param.UserID, - Type: model.MsgTypeWhisper, + Type: core.MsgTypeWhisper, Brief: "给你发送新私信了", Content: param.Content, }) diff --git a/internal/routers/api/post.go b/internal/servants/web/routers/api/post.go similarity index 79% rename from internal/routers/api/post.go rename to internal/servants/web/routers/api/post.go index f580428f..9ca19f3f 100644 --- a/internal/routers/api/post.go +++ b/internal/servants/web/routers/api/post.go @@ -1,10 +1,13 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -25,7 +28,7 @@ func GetPostList(c *gin.Context) { user, _ := userFrom(c) offset, limit := app.GetPageOffset(c) if q.Query == "" && q.Type == "search" { - resp, err := service.GetIndexPosts(user, offset, limit) + resp, err := broker.GetIndexPosts(user, offset, limit) if err != nil { logrus.Errorf("service.GetPostList err: %v\n", err) response.ToErrorResponse(errcode.GetPostsFailed) @@ -34,7 +37,7 @@ func GetPostList(c *gin.Context) { response.ToResponseList(resp.Tweets, resp.Total) } else { - posts, totalRows, err := service.GetPostListFromSearch(user, q, offset, limit) + posts, totalRows, err := broker.GetPostListFromSearch(user, q, offset, limit) if err != nil { logrus.Errorf("service.GetPostListFromSearch err: %v\n", err) @@ -49,7 +52,7 @@ func GetPost(c *gin.Context) { postID := convert.StrTo(c.Query("id")).MustInt64() response := app.NewResponse(c) - postFormated, err := service.GetPost(postID) + postFormated, err := broker.GetPost(postID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) @@ -61,7 +64,7 @@ func GetPost(c *gin.Context) { } func CreatePost(c *gin.Context) { - param := service.PostCreationReq{} + param := broker.PostCreationReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -71,7 +74,7 @@ func CreatePost(c *gin.Context) { } userID, _ := c.Get("UID") - post, err := service.CreatePost(c, userID.(int64), param) + post, err := broker.CreatePost(c, userID.(int64), param) if err != nil { logrus.Errorf("service.CreatePost err: %v\n", err) @@ -83,7 +86,7 @@ func CreatePost(c *gin.Context) { } func DeletePost(c *gin.Context) { - param := service.PostDelReq{} + param := broker.PostDelReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -98,7 +101,7 @@ func DeletePost(c *gin.Context) { return } - err := service.DeletePost(user, param.ID) + err := broker.DeletePost(user, param.ID) if err != nil { logrus.Errorf("service.DeletePost err: %v\n", err) response.ToErrorResponse(err) @@ -114,7 +117,7 @@ func GetPostStar(c *gin.Context) { userID, _ := c.Get("UID") - _, err := service.GetPostStar(postID, userID.(int64)) + _, err := broker.GetPostStar(postID, userID.(int64)) if err != nil { response.ToResponse(gin.H{ "status": false, @@ -129,7 +132,7 @@ func GetPostStar(c *gin.Context) { } func PostStar(c *gin.Context) { - param := service.PostStarReq{} + param := broker.PostStarReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -141,14 +144,14 @@ func PostStar(c *gin.Context) { userID, _ := c.Get("UID") status := false - star, err := service.GetPostStar(param.ID, userID.(int64)) + star, err := broker.GetPostStar(param.ID, userID.(int64)) if err != nil { // 创建Star - _, err = service.CreatePostStar(param.ID, userID.(int64)) + _, err = broker.CreatePostStar(param.ID, userID.(int64)) status = true } else { // 取消Star - err = service.DeletePostStar(star) + err = broker.DeletePostStar(star) } if err != nil { @@ -167,7 +170,7 @@ func GetPostCollection(c *gin.Context) { userID, _ := c.Get("UID") - _, err := service.GetPostCollection(postID, userID.(int64)) + _, err := broker.GetPostCollection(postID, userID.(int64)) if err != nil { response.ToResponse(gin.H{ "status": false, @@ -182,7 +185,7 @@ func GetPostCollection(c *gin.Context) { } func PostCollection(c *gin.Context) { - param := service.PostCollectionReq{} + param := broker.PostCollectionReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -194,14 +197,14 @@ func PostCollection(c *gin.Context) { userID, _ := c.Get("UID") status := false - collection, err := service.GetPostCollection(param.ID, userID.(int64)) + collection, err := broker.GetPostCollection(param.ID, userID.(int64)) if err != nil { // 创建collection - _, err = service.CreatePostCollection(param.ID, userID.(int64)) + _, err = broker.CreatePostCollection(param.ID, userID.(int64)) status = true } else { // 取消Star - err = service.DeletePostCollection(collection) + err = broker.DeletePostCollection(collection) } if err != nil { @@ -215,7 +218,7 @@ func PostCollection(c *gin.Context) { } func LockPost(c *gin.Context) { - param := service.PostLockReq{} + param := broker.PostLockReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -227,18 +230,18 @@ func LockPost(c *gin.Context) { user, _ := c.Get("USER") // 获取Post - postFormated, err := service.GetPost(param.ID) + postFormated, err := broker.GetPost(param.ID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) response.ToErrorResponse(errcode.GetPostFailed) return } - if postFormated.UserID != user.(*model.User).ID && !user.(*model.User).IsAdmin { + if postFormated.UserID != user.(*core.User).ID && !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } - err = service.LockPost(param.ID) + err = broker.LockPost(param.ID) if err != nil { logrus.Errorf("service.LockPost err: %v\n", err) response.ToErrorResponse(errcode.LockPostFailed) @@ -251,7 +254,7 @@ func LockPost(c *gin.Context) { } func StickPost(c *gin.Context) { - param := service.PostStickReq{} + param := broker.PostStickReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -263,18 +266,18 @@ func StickPost(c *gin.Context) { user, _ := c.Get("USER") // 获取Post - postFormated, err := service.GetPost(param.ID) + postFormated, err := broker.GetPost(param.ID) if err != nil { logrus.Errorf("service.GetPost err: %v\n", err) response.ToErrorResponse(errcode.GetPostFailed) return } - if !user.(*model.User).IsAdmin { + if !user.(*core.User).IsAdmin { response.ToErrorResponse(errcode.NoPermission) return } - err = service.StickPost(param.ID) + err = broker.StickPost(param.ID) if err != nil { logrus.Errorf("service.StickPost err: %v\n", err) response.ToErrorResponse(errcode.LockPostFailed) @@ -287,7 +290,7 @@ func StickPost(c *gin.Context) { } func VisiblePost(c *gin.Context) { - param := service.PostVisibilityReq{} + param := broker.PostVisibilityReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -297,7 +300,7 @@ func VisiblePost(c *gin.Context) { } user, _ := userFrom(c) - if err := service.VisiblePost(user, param.ID, param.Visibility); err != nil { + if err := broker.VisiblePost(user, param.ID, param.Visibility); err != nil { logrus.Errorf("service.VisiblePost err: %v\n", err) response.ToErrorResponse(err) return @@ -309,7 +312,7 @@ func VisiblePost(c *gin.Context) { } func GetPostTags(c *gin.Context) { - param := service.PostTagsReq{} + param := broker.PostTagsReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -318,7 +321,7 @@ func GetPostTags(c *gin.Context) { return } - tags, err := service.GetPostTags(¶m) + tags, err := broker.GetPostTags(¶m) if err != nil { logrus.Errorf("service.GetPostTags err: %v\n", err) response.ToErrorResponse(errcode.GetPostTagsFailed) diff --git a/internal/routers/api/user.go b/internal/servants/web/routers/api/user.go similarity index 80% rename from internal/routers/api/user.go rename to internal/servants/web/routers/api/user.go index 7541c54b..f45ff8ce 100644 --- a/internal/routers/api/user.go +++ b/internal/servants/web/routers/api/user.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package api import ( @@ -6,9 +10,8 @@ import ( "unicode/utf8" "github.com/gin-gonic/gin" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/internal/model/rest" - "github.com/rocboss/paopao-ce/internal/service" + "github.com/rocboss/paopao-ce/internal/core" + "github.com/rocboss/paopao-ce/internal/servants/web/broker" "github.com/rocboss/paopao-ce/pkg/app" "github.com/rocboss/paopao-ce/pkg/convert" "github.com/rocboss/paopao-ce/pkg/errcode" @@ -18,7 +21,7 @@ import ( // Login 用户登录 func Login(c *gin.Context) { - param := service.AuthRequest{} + param := broker.AuthRequest{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -27,7 +30,7 @@ func Login(c *gin.Context) { return } - user, err := service.DoLogin(c, ¶m) + user, err := broker.DoLogin(c, ¶m) if err != nil { logrus.Errorf("service.DoLogin err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -49,7 +52,7 @@ func Login(c *gin.Context) { // Register 用户注册 func Register(c *gin.Context) { - param := service.RegisterRequest{} + param := broker.RegisterRequest{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -59,7 +62,7 @@ func Register(c *gin.Context) { } // 用户名检查 - err := service.ValidUsername(param.Username) + err := broker.ValidUsername(param.Username) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -67,14 +70,14 @@ func Register(c *gin.Context) { } // 密码检查 - err = service.CheckPassword(param.Password) + err = broker.CheckPassword(param.Password) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) return } - user, err := service.Register( + user, err := broker.Register( param.Username, param.Password, ) @@ -92,7 +95,7 @@ func Register(c *gin.Context) { } func RequestingFriend(c *gin.Context) { - param := rest.RequestingFriendReq{} + param := broker.RequestingFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -110,7 +113,7 @@ func RequestingFriend(c *gin.Context) { return } - if err := service.RequestingFriend(user, ¶m); err != nil { + if err := broker.RequestingFriend(user, ¶m); err != nil { logrus.Errorf("service.RequestingFriend err: %v", err) response.ToErrorResponse(errcode.SendRequestingFriendFailed) return @@ -120,7 +123,7 @@ func RequestingFriend(c *gin.Context) { } func AddFriend(c *gin.Context) { - param := rest.AddFriendReq{} + param := broker.AddFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -137,7 +140,7 @@ func AddFriend(c *gin.Context) { return } - if err := service.AddFriend(user, ¶m); err != nil { + if err := broker.AddFriend(user, ¶m); err != nil { logrus.Errorf("service.AddFriend err: %v", err) response.ToErrorResponse(errcode.AddFriendFailed) return @@ -147,7 +150,7 @@ func AddFriend(c *gin.Context) { } func RejectFriend(c *gin.Context) { - param := rest.RejectFriendReq{} + param := broker.RejectFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -164,7 +167,7 @@ func RejectFriend(c *gin.Context) { return } - if err := service.RejectFriend(user, ¶m); err != nil { + if err := broker.RejectFriend(user, ¶m); err != nil { logrus.Errorf("service.RejectFriend err: %v", err) response.ToErrorResponse(errcode.RejectFriendFailed) return @@ -174,7 +177,7 @@ func RejectFriend(c *gin.Context) { } func DeleteFriend(c *gin.Context) { - param := rest.DeleteFriendReq{} + param := broker.DeleteFriendReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -191,7 +194,7 @@ func DeleteFriend(c *gin.Context) { return } - if err := service.DeleteFriend(user, ¶m); err != nil { + if err := broker.DeleteFriend(user, ¶m); err != nil { logrus.Errorf("service.DeleteFriend err: %v", err) response.ToErrorResponse(errcode.DeleteFriendFailed) return @@ -208,7 +211,7 @@ func GetContacts(c *gin.Context) { } offset, limit := app.GetPageOffset(c) - resp, err := service.GetContacts(user, offset, limit) + resp, err := broker.GetContacts(user, offset, limit) if err != nil { logrus.Errorf("service.DeleteFriend err: %v", err) response.ToErrorResponse(errcode.GetContactsFailed) @@ -219,14 +222,14 @@ func GetContacts(c *gin.Context) { // 获取用户基本信息 func GetUserInfo(c *gin.Context) { - param := service.AuthRequest{} + param := broker.AuthRequest{} response := app.NewResponse(c) if username, exists := c.Get("USERNAME"); exists { param.Username = username.(string) } - user, err := service.GetUserInfo(¶m) + user, err := broker.GetUserInfo(¶m) if err != nil { response.ToErrorResponse(errcode.UnauthorizedAuthNotExist) @@ -251,7 +254,7 @@ func GetUserInfo(c *gin.Context) { // 修改密码 func ChangeUserPassword(c *gin.Context) { - param := service.ChangePasswordReq{} + param := broker.ChangePasswordReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -260,13 +263,13 @@ func ChangeUserPassword(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } // 密码检查 - err := service.CheckPassword(param.Password) + err := broker.CheckPassword(param.Password) if err != nil { logrus.Errorf("service.Register err: %v", err) response.ToErrorResponse(err.(*errcode.Error)) @@ -274,21 +277,21 @@ func ChangeUserPassword(c *gin.Context) { } // 旧密码校验 - if !service.ValidPassword(user.Password, param.OldPassword, user.Salt) { + if !broker.ValidPassword(user.Password, param.OldPassword, user.Salt) { response.ToErrorResponse(errcode.ErrorOldPassword) return } // 更新入库 - user.Password, user.Salt = service.EncryptPasswordAndSalt(param.Password) - service.UpdateUserInfo(user) + user.Password, user.Salt = broker.EncryptPasswordAndSalt(param.Password) + broker.UpdateUserInfo(user) response.ToResponse(nil) } // 修改昵称 func ChangeNickname(c *gin.Context) { - param := service.ChangeNicknameReq{} + param := broker.ChangeNicknameReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -297,9 +300,9 @@ func ChangeNickname(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } if utf8.RuneCountInString(param.Nickname) < 2 || utf8.RuneCountInString(param.Nickname) > 12 { @@ -309,14 +312,14 @@ func ChangeNickname(c *gin.Context) { // 执行绑定 user.Nickname = param.Nickname - service.UpdateUserInfo(user) + broker.UpdateUserInfo(user) response.ToResponse(nil) } // 修改头像 func ChangeAvatar(c *gin.Context) { - param := service.ChangeAvatarReq{} + param := broker.ChangeAvatarReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -331,7 +334,7 @@ func ChangeAvatar(c *gin.Context) { return } - if err := service.ChangeUserAvatar(user, param.Avatar); err != nil { + if err := broker.ChangeUserAvatar(user, param.Avatar); err != nil { response.ToErrorResponse(err) return } @@ -340,7 +343,7 @@ func ChangeAvatar(c *gin.Context) { // 用户绑定手机号 func BindUserPhone(c *gin.Context) { - param := service.UserPhoneBindReq{} + param := broker.UserPhoneBindReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -349,18 +352,18 @@ func BindUserPhone(c *gin.Context) { return } - user := &model.User{} + user := &core.User{} if u, exists := c.Get("USER"); exists { - user = u.(*model.User) + user = u.(*core.User) } // 手机重复性检查 - if service.CheckPhoneExist(user.ID, param.Phone) { + if broker.CheckPhoneExist(user.ID, param.Phone) { response.ToErrorResponse(errcode.ExistedUserPhone) return } - if err := service.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil { + if err := broker.CheckPhoneCaptcha(param.Phone, param.Captcha); err != nil { logrus.Errorf("service.CheckPhoneCaptcha err: %v\n", err) response.ToErrorResponse(err) return @@ -368,7 +371,7 @@ func BindUserPhone(c *gin.Context) { // 执行绑定 user.Phone = param.Phone - if err := service.UpdateUserInfo(user); err != nil { + if err := broker.UpdateUserInfo(user); err != nil { response.ToErrorResponse(err) return } @@ -378,7 +381,7 @@ func BindUserPhone(c *gin.Context) { // 修改用户状态 func ChangeUserStatus(c *gin.Context) { - param := service.ChangeUserStatusReq{} + param := broker.ChangeUserStatusReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -387,12 +390,12 @@ func ChangeUserStatus(c *gin.Context) { return } - if param.Status != model.UserStatusNormal && param.Status != model.UserStatusClosed { + if param.Status != core.UserStatusNormal && param.Status != core.UserStatusClosed { response.ToErrorResponse(errcode.InvalidParams) return } - user, err := service.GetUserByID(param.ID) + user, err := broker.GetUserByID(param.ID) if err != nil { logrus.Errorf("service.GetUserByID err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) @@ -401,7 +404,7 @@ func ChangeUserStatus(c *gin.Context) { // 执行更新 user.Status = param.Status - service.UpdateUserInfo(user) + broker.UpdateUserInfo(user) response.ToResponse(nil) } @@ -411,7 +414,7 @@ func GetUserProfile(c *gin.Context) { username := c.Query("username") user, _ := userFrom(c) - resp, err := service.GetUserByUsername(user, username) + resp, err := broker.GetUserByUsername(user, username) if err != nil { logrus.Errorf("service.GetUserByUsername err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) @@ -426,28 +429,28 @@ func GetUserPosts(c *gin.Context) { username := c.Query("username") user, exists := userFrom(c) - other, err := service.GetUserByUsername(user, username) + other, err := broker.GetUserByUsername(user, username) if err != nil { logrus.Errorf("service.GetUserByUsername err: %v\n", err) response.ToErrorResponse(errcode.NoExistUsername) return } - visibilities := []model.PostVisibleT{model.PostVisitPublic} + visibilities := []core.PostVisibleT{core.PostVisitPublic} if exists { if user.ID == other.ID || user.IsAdmin { - visibilities = append(visibilities, model.PostVisitPrivate, model.PostVisitFriend) + visibilities = append(visibilities, core.PostVisitPrivate, core.PostVisitFriend) } else if other.IsFriend { - visibilities = append(visibilities, model.PostVisitFriend) + visibilities = append(visibilities, core.PostVisitFriend) } } - conditions := model.ConditionsT{ + conditions := core.ConditionsT{ "user_id": other.ID, "visibility IN ?": visibilities, "ORDER": "latest_replied_on DESC", } - _, posts, err := service.GetPostList(&service.PostListReq{ + _, posts, err := broker.GetPostList(&broker.PostListReq{ Conditions: &conditions, Offset: (app.GetPage(c) - 1) * app.GetPageSize(c), Limit: app.GetPageSize(c), @@ -457,7 +460,7 @@ func GetUserPosts(c *gin.Context) { response.ToErrorResponse(errcode.GetPostsFailed) return } - totalRows, _ := service.GetPostCount(&conditions) + totalRows, _ := broker.GetPostCount(&conditions) response.ToResponseList(posts, totalRows) } @@ -466,7 +469,7 @@ func GetUserCollections(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - posts, totalRows, err := service.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + posts, totalRows, err := broker.GetUserCollections(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserCollections err: %v\n", err) @@ -481,7 +484,7 @@ func GetUserStars(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - posts, totalRows, err := service.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + posts, totalRows, err := broker.GetUserStars(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserStars err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -495,7 +498,7 @@ func GetSuggestUsers(c *gin.Context) { keyword := c.Query("k") response := app.NewResponse(c) - usernames, err := service.GetSuggestUsers(keyword) + usernames, err := broker.GetSuggestUsers(keyword) if err != nil { logrus.Errorf("service.GetSuggestUsers err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -509,7 +512,7 @@ func GetSuggestTags(c *gin.Context) { keyword := c.Query("k") response := app.NewResponse(c) - tags, err := service.GetSuggestTags(keyword) + tags, err := broker.GetSuggestTags(keyword) if err != nil { logrus.Errorf("service.GetSuggestTags err: %v\n", err) response.ToErrorResponse(errcode.GetCollectionsFailed) @@ -520,7 +523,7 @@ func GetSuggestTags(c *gin.Context) { } func GetUserRechargeLink(c *gin.Context) { - param := service.RechargeReq{} + param := broker.RechargeReq{} response := app.NewResponse(c) valid, errs := app.BindAndValid(c, ¶m) if !valid { @@ -531,7 +534,7 @@ func GetUserRechargeLink(c *gin.Context) { // 下单 userID, _ := c.Get("UID") - recharge, err := service.CreateRecharge(userID.(int64), param.Amount) + recharge, err := broker.CreateRecharge(userID.(int64), param.Amount) if err != nil { logrus.Errorf("service.CreateRecharge err: %v\n", err) response.ToErrorResponse(errcode.RechargeReqFail) @@ -567,7 +570,7 @@ func GetUserRechargeResult(c *gin.Context) { id := c.Query("id") userID, _ := c.Get("UID") - recharge, err := service.GetRechargeByID(convert.StrTo(id).MustInt64()) + recharge, err := broker.GetRechargeByID(convert.StrTo(id).MustInt64()) if err != nil { response.ToErrorResponse(errcode.GetRechargeFailed) return @@ -601,7 +604,7 @@ func AlipayNotify(c *gin.Context) { tradeStatus := c.Request.Form.Get("trade_status") if tradeStatus == "TRADE_SUCCESS" { // 交易支付成功 - err = service.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo) + err = broker.FinishRecharge(c, convert.StrTo(id).MustInt64(), tradeNo) if err != nil { logrus.Errorf("service.FinishRecharge err: %v\n", err) response.ToErrorResponse(errcode.RechargeNotifyError) @@ -615,7 +618,7 @@ func GetUserWalletBills(c *gin.Context) { response := app.NewResponse(c) userID, _ := c.Get("UID") - bills, totalRows, err := service.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) + bills, totalRows, err := broker.GetUserWalletBills(userID.(int64), (app.GetPage(c)-1)*app.GetPageSize(c), app.GetPageSize(c)) if err != nil { logrus.Errorf("service.GetUserWalletBills err: %v\n", err) @@ -626,9 +629,9 @@ func GetUserWalletBills(c *gin.Context) { response.ToResponseList(bills, totalRows) } -func userFrom(c *gin.Context) (*model.User, bool) { +func userFrom(c *gin.Context) (*core.User, bool) { if u, exists := c.Get("USER"); exists { - user, ok := u.(*model.User) + user, ok := u.(*core.User) return user, ok } return nil, false diff --git a/internal/routers/docs.go b/internal/servants/web/routers/docs.go similarity index 57% rename from internal/routers/docs.go rename to internal/servants/web/routers/docs.go index fc054b08..bf5e0488 100644 --- a/internal/routers/docs.go +++ b/internal/servants/web/routers/docs.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !docs // +build !docs diff --git a/internal/routers/docs_embed.go b/internal/servants/web/routers/docs_embed.go similarity index 69% rename from internal/routers/docs_embed.go rename to internal/servants/web/routers/docs_embed.go index e9c0d17d..a636e487 100644 --- a/internal/routers/docs_embed.go +++ b/internal/servants/web/routers/docs_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build docs // +build docs diff --git a/internal/routers/router.go b/internal/servants/web/routers/router.go similarity index 76% rename from internal/routers/router.go rename to internal/servants/web/routers/router.go index 1a2b57f6..e46b533b 100644 --- a/internal/routers/router.go +++ b/internal/servants/web/routers/router.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package routers import ( @@ -7,8 +11,8 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/middleware" - "github.com/rocboss/paopao-ce/internal/routers/api" + "github.com/rocboss/paopao-ce/internal/servants/chain" + "github.com/rocboss/paopao-ce/internal/servants/web/routers/api" "github.com/rocboss/paopao-ce/pkg/cfg" "github.com/sirupsen/logrus" ) @@ -67,7 +71,7 @@ func NewRouter() *gin.Engine { } // 宽松鉴权路由组 - looseApi := r.Group("/").Use(middleware.JwtLoose()) + looseApi := r.Group("/").Use(chain.JwtLoose()) { // 获取广场流 looseApi.GET("/posts", api.GetPostList) @@ -80,9 +84,9 @@ func NewRouter() *gin.Engine { } // 鉴权路由组 - authApi := r.Group("/").Use(middleware.JWT()) - privApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Priv()) - adminApi := r.Group("/").Use(middleware.JWT()).Use(middleware.Admin()) + authApi := r.Group("/").Use(chain.JWT()) + privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv()) + adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin()) // 核心路由注册 routeCore(authApi, privApi, adminApi) @@ -114,6 +118,78 @@ func NewRouter() *gin.Engine { return e } +func RegisterRoute(e *gin.Engine) { + // 按需注册 docs、静态资源、LocalOSS 路由 + { + registerDocs(e) + registerStatick(e) + + cfg.Be("LocalOSS", func() { + routeLocalOSS(e) + }) + } + + // v1 group api + r := e.Group("/v1") + + // 获取version + r.GET("/", api.Version) + + // 用户登录 + r.POST("/auth/login", api.Login) + + // 用户注册 + r.POST("/auth/register", api.Register) + + // 获取验证码 + r.GET("/captcha", api.GetCaptcha) + + // 发送验证码 + r.POST("/captcha", api.PostCaptcha) + + // 无鉴权路由组 + noAuthApi := r.Group("/") + { + // 获取动态详情 + noAuthApi.GET("/post", api.GetPost) + + // 获取动态评论 + noAuthApi.GET("/post/comments", api.GetPostComments) + + // 获取话题列表 + noAuthApi.GET("/tags", api.GetPostTags) + } + + // 宽松鉴权路由组 + looseApi := r.Group("/").Use(chain.JwtLoose()) + { + // 获取广场流 + looseApi.GET("/posts", api.GetPostList) + + // 获取用户动态列表 + looseApi.GET("/user/posts", api.GetUserPosts) + + // 获取用户基本信息 + looseApi.GET("/user/profile", api.GetUserProfile) + } + + // 鉴权路由组 + authApi := r.Group("/").Use(chain.JWT()) + privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv()) + adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin()) + + // 核心路由注册 + routeCore(authApi, privApi, adminApi) + + // 支付宝路由注册 + cfg.Be("Alipay", func() { + routeAlipay(r, authApi) + }) + + // Relationship相关路由注册 + routeRelationship(authApi) +} + func routeCore(authApi gin.IRoutes, privApi gin.IRoutes, adminApi gin.IRoutes) { // 同步索引 authApi.GET("/sync/index", api.SyncSearchIndex) diff --git a/internal/routers/statick.go b/internal/servants/web/routers/statick.go similarity index 58% rename from internal/routers/statick.go rename to internal/servants/web/routers/statick.go index c20d5059..c1f2d1cb 100644 --- a/internal/routers/statick.go +++ b/internal/servants/web/routers/statick.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build !embed // +build !embed diff --git a/internal/routers/statick_embed.go b/internal/servants/web/routers/statick_embed.go similarity index 79% rename from internal/routers/statick_embed.go rename to internal/servants/web/routers/statick_embed.go index 2ea56171..dfc729f5 100644 --- a/internal/routers/statick_embed.go +++ b/internal/servants/web/routers/statick_embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build embed // +build embed diff --git a/internal/servants/web/web.go b/internal/servants/web/web.go new file mode 100644 index 00000000..76ac9dd3 --- /dev/null +++ b/internal/servants/web/web.go @@ -0,0 +1,15 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +import ( + "github.com/gin-gonic/gin" + api "github.com/rocboss/paopao-ce/internal/mirc/auto/api/v1" +) + +// RouteWeb register web route +func RouteWeb(e *gin.Engine) { + api.RegisterWebCoreServant(e, newWebCoreSrv(), newWebCoreBinding(), newWebCoreRender()) +} diff --git a/internal/servants/web/xerror.go b/internal/servants/web/xerror.go new file mode 100644 index 00000000..ecc0355e --- /dev/null +++ b/internal/servants/web/xerror.go @@ -0,0 +1,77 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package web + +import ( + "github.com/rocboss/paopao-ce/pkg/xerror" +) + +var ( + errUsernameHasExisted = xerror.NewError(20001, "用户名已存在") + errUsernameLengthLimit = xerror.NewError(20002, "用户名长度3~12") + errUsernameCharLimit = xerror.NewError(20003, "用户名只能包含字母、数字") + errPasswordLengthLimit = xerror.NewError(20004, "密码长度6~16") + errUserRegisterFailed = xerror.NewError(20005, "用户注册失败") + errUserHasBeenBanned = xerror.NewError(20006, "该账户已被封停") + errNoPermission = xerror.NewError(20007, "无权限执行该请求") + errUserHasBindOTP = xerror.NewError(20008, "当前用户已绑定二次验证") + errUserOTPInvalid = xerror.NewError(20009, "二次验证码验证失败") + errUserNoBindOTP = xerror.NewError(20010, "当前用户未绑定二次验证") + errErrorOldPassword = xerror.NewError(20011, "当前用户密码验证失败") + errErrorCaptchaPassword = xerror.NewError(20012, "图形验证码验证失败") + errAccountNoPhoneBind = xerror.NewError(20013, "拒绝操作: 账户未绑定手机号") + errTooManyLoginError = xerror.NewError(20014, "登录失败次数过多,请稍后再试") + errGetPhoneCaptchaError = xerror.NewError(20015, "短信验证码获取失败") + errTooManyPhoneCaptchaSend = xerror.NewError(20016, "短信验证码获取次数已达今日上限") + errExistedUserPhone = xerror.NewError(20017, "该手机号已被绑定") + errErrorPhoneCaptcha = xerror.NewError(20018, "手机验证码不正确") + errMaxPhoneCaptchaUseTimes = xerror.NewError(20019, "手机验证码已达最大使用次数") + errNicknameLengthLimit = xerror.NewError(20020, "昵称长度2~12") + errNoExistUsername = xerror.NewError(20021, "用户不存在") + errNoAdminPermission = xerror.NewError(20022, "无管理权限") + + errGetPostsFailed = xerror.NewError(30001, "获取动态列表失败") + errCreatePostFailed = xerror.NewError(30002, "动态发布失败") + errGetPostFailed = xerror.NewError(30003, "获取动态详情失败") + errDeletePostFailed = xerror.NewError(30004, "动态删除失败") + errLockPostFailed = xerror.NewError(30005, "动态锁定失败") + errGetPostTagsFailed = xerror.NewError(30006, "获取话题列表失败") + errInvalidDownloadReq = xerror.NewError(30007, "附件下载请求不合法") + errDownloadReqError = xerror.NewError(30008, "附件下载请求失败") + errInsuffientDownloadMoney = xerror.NewError(30009, "附件下载失败:账户资金不足") + errDownloadExecFail = xerror.NewError(30010, "附件下载失败:扣费失败") + errStickPostFailed = xerror.NewError(30011, "动态置顶失败") + errVisblePostFailed = xerror.NewError(30012, "更新可见性失败") + + errGetCommentsFailed = xerror.NewError(40001, "获取评论列表失败") + errCreateCommentFailed = xerror.NewError(40002, "评论发布失败") + errGetCommentFailed = xerror.NewError(40003, "获取评论详情失败") + errDeleteCommentFailed = xerror.NewError(40004, "评论删除失败") + errCreateReplyFailed = xerror.NewError(40005, "评论回复失败") + errGetReplyFailed = xerror.NewError(40006, "获取评论详情失败") + errMaxCommentCount = xerror.NewError(40007, "评论数已达最大限制") + + errGetMessagesFailed = xerror.NewError(50001, "获取消息列表失败") + errReadMessageFailed = xerror.NewError(50002, "标记消息已读失败") + errSendWhisperFailed = xerror.NewError(50003, "私信发送失败") + errNoWhisperToSelf = xerror.NewError(50004, "不允许给自己发送私信") + errTooManyWhisperNum = xerror.NewError(50005, "今日私信次数已达上限") + + errGetCollectionsFailed = xerror.NewError(60001, "获取收藏列表失败") + errGetStarsFailed = xerror.NewError(60002, "获取点赞列表失败") + + errRechargeReqFail = xerror.NewError(70001, "充值请求失败") + errRechargeNotifyError = xerror.NewError(70002, "充值回调失败") + errGetRechargeFailed = xerror.NewError(70003, "充值详情获取失败") + + errNoRequestingFriendToSelf = xerror.NewError(80001, "不允许添加自己为好友") + errNotExistFriendId = xerror.NewError(80002, "好友id不存在") + errSendRequestingFriendFailed = xerror.NewError(80003, "申请添加朋友请求发送失败") + errAddFriendFailed = xerror.NewError(80004, "添加好友失败") + errRejectFriendFailed = xerror.NewError(80005, "拒绝好友失败") + errDeleteFriendFailed = xerror.NewError(80006, "删除好友失败") + errGetContactsFailed = xerror.NewError(80007, "获取联系人列表失败") + errNoActionToSelf = xerror.NewError(80008, "不允许对自己操作") +) diff --git a/internal/service/attachment.go b/internal/service/attachment.go deleted file mode 100644 index 432a1a2f..00000000 --- a/internal/service/attachment.go +++ /dev/null @@ -1,7 +0,0 @@ -package service - -import "github.com/rocboss/paopao-ce/internal/model" - -func CreateAttachment(attachment *model.Attachment) (*model.Attachment, error) { - return ds.CreateAttachment(attachment) -} diff --git a/internal/service/http_server.go b/internal/service/http_server.go new file mode 100644 index 00000000..4a8fdf3b --- /dev/null +++ b/internal/service/http_server.go @@ -0,0 +1,83 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "context" + "net/http" + "sync" + + "github.com/gin-gonic/gin" +) + +var ( + httpServers = make(map[string]*httpServer) +) + +const ( + httpServerInitilized uint8 = iota + 1 + httpServerStarted + httpServerStoped +) + +// httpServer wraper for gin.engine and http.Server +type httpServer struct { + sync.RWMutex + + e *gin.Engine + server *http.Server + serverStatus uint8 +} + +func (s *httpServer) status() uint8 { + s.RLock() + defer s.RUnlock() + + return s.serverStatus +} + +func (s *httpServer) start() error { + s.Lock() + if s.serverStatus == httpServerStarted || s.serverStatus == httpServerStoped { + return nil + } + oldStatus := s.serverStatus + s.serverStatus = httpServerStarted + s.Unlock() + + if err := s.server.ListenAndServe(); err != nil { + s.Lock() + s.serverStatus = oldStatus + s.Unlock() + + return err + } + return nil +} + +func (s *httpServer) stop() error { + s.Lock() + defer s.Unlock() + + if s.serverStatus == httpServerStoped || s.serverStatus == httpServerInitilized { + return nil + } + if err := s.server.Shutdown(context.Background()); err != nil { + return err + } + s.serverStatus = httpServerStoped + return nil +} + +func httpServerFrom(addr string, newServer func() *httpServer) *httpServer { + s, exist := httpServers[addr] + if exist { + return s + } + s = newServer() + s.serverStatus = httpServerInitilized + httpServers[addr] = s + return s +} diff --git a/internal/service/http_service.go b/internal/service/http_service.go new file mode 100644 index 00000000..fc7ce9b6 --- /dev/null +++ b/internal/service/http_service.go @@ -0,0 +1,32 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "github.com/gin-gonic/gin" +) + +type baseHttpService struct { + baseService + + server *httpServer +} + +func (s *baseHttpService) registerRoute(h func(e *gin.Engine)) { + if s.server.status() != httpServerStarted { + h(s.server.e) + } +} + +func (s *baseHttpService) Start() error { + if err := s.server.start(); err != nil { + return err + } + return nil +} + +func (s *baseHttpService) Stop() error { + return s.server.stop() +} diff --git a/internal/service/service.go b/internal/service/service.go index 9d7d4c01..9ac6446c 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1,44 +1,38 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package service import ( - "github.com/rocboss/paopao-ce/internal/core" - "github.com/rocboss/paopao-ce/internal/dao" - "github.com/rocboss/paopao-ce/internal/model" - "github.com/rocboss/paopao-ce/pkg/cfg" - "github.com/sirupsen/logrus" -) + "log" -var ( - ds core.DataService - ts core.TweetSearchService - oss core.ObjectStorageService - DisablePhoneVerify bool + "github.com/rocboss/paopao-ce/pkg/types" ) -func Initialize() { - ds = dao.DataService() - ts = dao.TweetSearchService() - oss = dao.ObjectStorageService() - DisablePhoneVerify = !cfg.If("Sms") +type Service interface { + Name() string + Init() error + Start() error + Stop() error +} + +type baseService types.Empty + +func (baseService) Name() string { + return "" +} + +func (baseService) String() string { + return "" } -// persistMediaContents 获取媒体内容并持久化 -func persistMediaContents(contents []*PostContentItem) (items []string, err error) { - items = make([]string, 0, len(contents)) - for _, item := range contents { - switch item.Type { - case model.CONTENT_TYPE_IMAGE, - model.CONTENT_TYPE_VIDEO, - model.CONTENT_TYPE_AUDIO, - model.CONTENT_TYPE_ATTACHMENT, - model.CONTENT_TYPE_CHARGE_ATTACHMENT: - items = append(items, item.Content) - if err != nil { - continue - } - if err = oss.PersistObject(oss.ObjectKey(item.Content)); err != nil { - logrus.Errorf("service.persistMediaContents failed: %s", err) - } +func InitService() (ss []Service) { + ss = append(ss, newWebService(), newOldWebService()) + + for _, s := range ss { + if err := s.Init(); err != nil { + log.Fatalf("initial %s service error: %s", s.Name(), err) } } return diff --git a/internal/service/web.go b/internal/service/web.go new file mode 100644 index 00000000..c8e422a1 --- /dev/null +++ b/internal/service/web.go @@ -0,0 +1,86 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants" +) + +type webService struct { + *baseHttpService +} + +func (s *webService) Name() string { + return "WebService" +} + +func (s *webService) Init() error { + s.registerRoute(servants.RegisterWebServants) + return nil +} + +func (s *webService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.WebServerSetting.HttpIp, conf.WebServerSetting.HttpPort)) +} + +func newWebEngine() *gin.Engine { + e := gin.New() + e.HandleMethodNotAllowed = true + e.Use(gin.Logger()) + e.Use(gin.Recovery()) + + // 跨域配置 + corsConfig := cors.DefaultConfig() + corsConfig.AllowAllOrigins = true + corsConfig.AddAllowHeaders("Authorization") + e.Use(cors.New(corsConfig)) + + // 默认404 + e.NoRoute(func(c *gin.Context) { + c.JSON(http.StatusNotFound, gin.H{ + "code": 404, + "msg": "Not Found", + }) + }) + + // 默认405 + e.NoMethod(func(c *gin.Context) { + c.JSON(http.StatusMethodNotAllowed, gin.H{ + "code": 405, + "msg": "Method Not Allowed", + }) + }) + + return e +} + +func newWebService() Service { + addr := conf.WebServerSetting.HttpIp + ":" + conf.WebServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newWebEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.WebServerSetting.ReadTimeout, + WriteTimeout: conf.WebServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &webService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/internal/service/web_old.go b/internal/service/web_old.go new file mode 100644 index 00000000..a3c58471 --- /dev/null +++ b/internal/service/web_old.go @@ -0,0 +1,53 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package service + +import ( + "fmt" + "net/http" + + "github.com/fatih/color" + "github.com/rocboss/paopao-ce/internal/conf" + "github.com/rocboss/paopao-ce/internal/servants/web/routers" +) + +type oldWebService struct { + *baseHttpService +} + +func (s *oldWebService) Name() string { + return "OldWebService" +} + +func (s *oldWebService) Init() error { + s.registerRoute(routers.RegisterRoute) + return nil +} + +func (s *oldWebService) String() string { + return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)) +} + +func newOldWebService() Service { + addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort + server := httpServerFrom(addr, func() *httpServer { + engine := newWebEngine() + return &httpServer{ + e: engine, + server: &http.Server{ + Addr: addr, + Handler: engine, + ReadTimeout: conf.ServerSetting.ReadTimeout, + WriteTimeout: conf.ServerSetting.WriteTimeout, + MaxHeaderBytes: 1 << 20, + }, + } + }) + return &oldWebService{ + baseHttpService: &baseHttpService{ + server: server, + }, + } +} diff --git a/main.go b/main.go index 1046e97d..63ec5f59 100644 --- a/main.go +++ b/main.go @@ -1,17 +1,23 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package main import ( "flag" "fmt" "log" - "net/http" + "os" + "os/signal" "strings" + "syscall" "github.com/fatih/color" "github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/routers" + "github.com/rocboss/paopao-ce/internal/service" "github.com/rocboss/paopao-ce/pkg/debug" "github.com/rocboss/paopao-ce/pkg/util" ) @@ -47,24 +53,41 @@ func flagParse() { flag.Parse() } -func main() { - gin.SetMode(conf.ServerSetting.RunMode) - - router := routers.NewRouter() - s := &http.Server{ - Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort, - Handler: router, - ReadTimeout: conf.ServerSetting.ReadTimeout, - WriteTimeout: conf.ServerSetting.WriteTimeout, - MaxHeaderBytes: 1 << 20, +func runService(ss []service.Service) { + gin.SetMode(conf.RunMode()) + + fmt.Fprintf(color.Output, "\nstarting run service...\n\n") + for _, s := range ss { + go func(s service.Service) { + fmt.Fprintf(color.Output, "%s[start] - %s\n", s.Name(), s) + if err := s.Start(); err != nil { + log.Fatalf("%s[start] - occurs on error: %s\n", s.Name(), err) + } + }(s) + } + + quit := make(chan os.Signal, 1) + // kill (no param) default send syscall.SIGTERM + // kill -2 is syscall.SIGINT + // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it + signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + <-quit + fmt.Fprintf(color.Output, "\nshutting down server...\n\n") + + for _, s := range ss { + if err := s.Stop(); err != nil { + fmt.Fprintf(color.Output, "%s[stop] - occurs on error: %s\n", s.Name(), err) + } + fmt.Fprintf(color.Output, "%s[stop] - finish...\n", s.Name()) } +} +func main() { util.PrintHelloBanner(debug.VersionInfo()) - fmt.Fprintf(color.Output, "PaoPao service listen on %s\n", - color.GreenString(fmt.Sprintf("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)), - ) - if err := s.ListenAndServe(); err != nil { - log.Fatalf("run app failed: %s", err) + if ss := service.InitService(); len(ss) > 0 { + runService(ss) + } else { + fmt.Fprintf(color.Output, "no service need start so just exit") } } diff --git a/pkg/app/app.go b/pkg/app/app.go index fc860d27..a98a49a2 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/app/form.go b/pkg/app/form.go index 7e376104..91b116a2 100644 --- a/pkg/app/form.go +++ b/pkg/app/form.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/app/jwt.go b/pkg/app/jwt.go index 8033296f..b9759e07 100644 --- a/pkg/app/jwt.go +++ b/pkg/app/jwt.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( @@ -5,7 +9,7 @@ import ( "github.com/golang-jwt/jwt/v4" "github.com/rocboss/paopao-ce/internal/conf" - "github.com/rocboss/paopao-ce/internal/model" + "github.com/rocboss/paopao-ce/internal/core" ) type Claims struct { @@ -18,7 +22,7 @@ func GetJWTSecret() []byte { return []byte(conf.JWTSetting.Secret) } -func GenerateToken(User *model.User) (string, error) { +func GenerateToken(User *core.User) (string, error) { expireTime := time.Now().Add(conf.JWTSetting.Expire) claims := Claims{ UID: User.ID, diff --git a/pkg/app/pagination.go b/pkg/app/pagination.go index 1888efb9..699d1dd2 100644 --- a/pkg/app/pagination.go +++ b/pkg/app/pagination.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package app import ( diff --git a/pkg/cfg/cfg.go b/pkg/cfg/cfg.go index 019deba9..f04dc297 100644 --- a/pkg/cfg/cfg.go +++ b/pkg/cfg/cfg.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg var ( diff --git a/pkg/cfg/cfg_test.go b/pkg/cfg/cfg_test.go index 0fccbce2..68a3ce74 100644 --- a/pkg/cfg/cfg_test.go +++ b/pkg/cfg/cfg_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/cfg/feature.go b/pkg/cfg/feature.go index a04d07ca..32810b47 100644 --- a/pkg/cfg/feature.go +++ b/pkg/cfg/feature.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/cfg/feature_test.go b/pkg/cfg/feature_test.go index 98e01ec7..21c44c72 100644 --- a/pkg/cfg/feature_test.go +++ b/pkg/cfg/feature_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package cfg import ( diff --git a/pkg/convert/convert.go b/pkg/convert/convert.go index 60dacf9b..ff3be5e5 100644 --- a/pkg/convert/convert.go +++ b/pkg/convert/convert.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package convert import "strconv" diff --git a/pkg/convert/convert_test.go b/pkg/convert/convert_test.go index a746e3e7..a31d13e6 100644 --- a/pkg/convert/convert_test.go +++ b/pkg/convert/convert_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package convert import ( diff --git a/pkg/crypto/signature.go b/pkg/crypto/signature.go index 7f18959a..20a6deaa 100644 --- a/pkg/crypto/signature.go +++ b/pkg/crypto/signature.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package crypto import ( diff --git a/pkg/debug/version.go b/pkg/debug/version.go index 485e8046..68236f05 100644 --- a/pkg/debug/version.go +++ b/pkg/debug/version.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package debug import ( diff --git a/pkg/errcode/common_code.go b/pkg/errcode/common_code.go index 75b220ee..1f15f8c5 100644 --- a/pkg/errcode/common_code.go +++ b/pkg/errcode/common_code.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode var ( diff --git a/pkg/errcode/errcode.go b/pkg/errcode/errcode.go index 50f04868..5143aabb 100644 --- a/pkg/errcode/errcode.go +++ b/pkg/errcode/errcode.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode import ( diff --git a/pkg/errcode/module_code.go b/pkg/errcode/module_code.go index 1c5b7215..9543624b 100644 --- a/pkg/errcode/module_code.go +++ b/pkg/errcode/module_code.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package errcode var ( diff --git a/pkg/sign/sign.go b/pkg/sign/sign.go index 717b8e54..fc7c10e9 100644 --- a/pkg/sign/sign.go +++ b/pkg/sign/sign.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package sign import ( diff --git a/pkg/types/types.go b/pkg/types/types.go index 2696f8b9..830c56c6 100644 --- a/pkg/types/types.go +++ b/pkg/types/types.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package types // Empty empty alias type diff --git a/pkg/util/banner.go b/pkg/util/banner.go index d41b5ae1..31e25ba9 100644 --- a/pkg/util/banner.go +++ b/pkg/util/banner.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "fmt" diff --git a/pkg/util/ip.go b/pkg/util/ip.go index 3aaa13c1..4561d8a6 100644 --- a/pkg/util/ip.go +++ b/pkg/util/ip.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "github.com/rocboss/paopao-ce/pkg/util/iploc" diff --git a/pkg/util/ip_test.go b/pkg/util/ip_test.go index 82976be8..0740ffd5 100644 --- a/pkg/util/ip_test.go +++ b/pkg/util/ip_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "testing" diff --git a/pkg/util/iploc/iploc.go b/pkg/util/iploc/iploc.go index a05f8d7e..449e52a9 100644 --- a/pkg/util/iploc/iploc.go +++ b/pkg/util/iploc/iploc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package iploc import ( diff --git a/pkg/util/iploc/iploc_test.go b/pkg/util/iploc/iploc_test.go index 4754e86d..a38bb106 100644 --- a/pkg/util/iploc/iploc_test.go +++ b/pkg/util/iploc/iploc_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package iploc import ( diff --git a/pkg/util/md5.go b/pkg/util/md5.go index 8a00f545..477cd5ff 100644 --- a/pkg/util/md5.go +++ b/pkg/util/md5.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import ( diff --git a/pkg/util/md5_test.go b/pkg/util/md5_test.go index 0bab593f..12c14c86 100644 --- a/pkg/util/md5_test.go +++ b/pkg/util/md5_test.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import "testing" diff --git a/pkg/util/str.go b/pkg/util/str.go index 35e034ab..8b62217d 100644 --- a/pkg/util/str.go +++ b/pkg/util/str.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package util import ( diff --git a/pkg/xerror/common.go b/pkg/xerror/common.go new file mode 100644 index 00000000..2852f6c2 --- /dev/null +++ b/pkg/xerror/common.go @@ -0,0 +1,26 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package xerror + +var ( + Success = NewError(0, "成功") + ServerError = NewError(10000, "服务内部错误") + InvalidParams = NewError(10001, "入参错误") + NotFound = NewError(10002, "找不到") + UnauthorizedAuthNotExist = NewError(10003, "账户不存在") + UnauthorizedAuthFailed = NewError(10004, "账户密码错误") + UnauthorizedTokenError = NewError(10005, "鉴权失败,Token 错误或丢失") + UnauthorizedTokenTimeout = NewError(10006, "鉴权失败,Token 超时") + UnauthorizedTokenGenerate = NewError(10007, "鉴权失败,Token 生成失败") + TooManyRequests = NewError(10008, "请求过多") + + GatewayMethodsLimit = NewError(10109, "网关仅接受GET或POST请求") + GatewayLostSign = NewError(10110, "网关请求缺少签名") + GatewayLostAppKey = NewError(10111, "网关请求缺少APP KEY") + GatewayAppKeyInvalid = NewError(10112, "网关请求无效APP KEY") + GatewayAppKeyClosed = NewError(10113, "网关请求APP KEY已停用") + GatewayParamSignError = NewError(10114, "网关请求参数签名错误") + GatewayTooManyRequests = NewError(10115, "网关请求频次超限") +) diff --git a/pkg/xerror/xerror.go b/pkg/xerror/xerror.go new file mode 100644 index 00000000..f614d18e --- /dev/null +++ b/pkg/xerror/xerror.go @@ -0,0 +1,104 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package xerror + +import ( + "fmt" + "net/http" + "strings" +) + +var ( + codes = map[int]string{} +) + +type Error struct { + code int + msg string + details []string +} + +type ValidError struct { + Message string +} + +type ValidErrors []*ValidError + +func (v *ValidError) Error() string { + return v.Message +} + +func (v ValidErrors) Error() string { + return strings.Join(v.Errors(), ",") +} + +func (v ValidErrors) Errors() []string { + var errs []string + for _, err := range v { + errs = append(errs, err.Error()) + } + return errs +} + +func NewError(code int, msg string) *Error { + if _, ok := codes[code]; ok { + panic(fmt.Sprintf("错误码 %d 已经存在,请更换一个", code)) + } + codes[code] = msg + return &Error{code: code, msg: msg} +} + +func (e *Error) Error() string { + return fmt.Sprintf("错误码: %d, 错误信息: %s", e.Code(), e.Msg()) +} + +func (e *Error) Code() int { + return e.code +} + +func (e *Error) Msg() string { + return e.msg +} + +func (e *Error) Msgf(args []any) string { + return fmt.Sprintf(e.msg, args...) +} + +func (e *Error) Details() []string { + return e.details +} + +func (e *Error) WithDetails(details ...string) *Error { + newError := *e + newError.details = []string{} + newError.details = append(newError.details, details...) + + return &newError +} + +func (e *Error) StatusCode() int { + switch e.Code() { + case Success.Code(): + return http.StatusOK + case ServerError.Code(): + return http.StatusInternalServerError + case InvalidParams.Code(): + return http.StatusBadRequest + case UnauthorizedAuthNotExist.Code(): + fallthrough + case UnauthorizedAuthFailed.Code(): + fallthrough + case UnauthorizedTokenError.Code(): + fallthrough + case UnauthorizedTokenGenerate.Code(): + fallthrough + case UnauthorizedTokenTimeout.Code(): + return http.StatusUnauthorized + case TooManyRequests.Code(): + return http.StatusTooManyRequests + } + + return http.StatusInternalServerError +} diff --git a/pkg/zinc/zinc.go b/pkg/zinc/zinc.go index ba1fb270..cc200a55 100644 --- a/pkg/zinc/zinc.go +++ b/pkg/zinc/zinc.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + package zinc import ( diff --git a/scripts/migration/embed.go b/scripts/migration/embed.go index 88e633c8..3f1eacda 100644 --- a/scripts/migration/embed.go +++ b/scripts/migration/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build migration // +build migration diff --git a/web/embed.go b/web/embed.go index 4866a53a..a16df24a 100644 --- a/web/embed.go +++ b/web/embed.go @@ -1,3 +1,7 @@ +// Copyright 2022 ROC. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + //go:build embed // +build embed