Merge remote-tracking branch 'origin/errcode' into errcode

# Conflicts:
#	internal/common/notification/conversation_notification.go
#	internal/common/notification/work_moments_notification.go
#	internal/rpc/conversation/conversaion.go
#	internal/rpc/group/callback.go
#	internal/rpc/group/group.go
#	internal/rpc/office/office.go
This commit is contained in:
skiffer-git 2023-02-10 21:05:49 +08:00
commit adc84b68e7
113 changed files with 1336 additions and 36247 deletions

2
.gitignore vendored
View File

@ -8,12 +8,10 @@ out-test
.idea
deploy/open_im_demo
deploy/open_im_api
deploy/open_im_msg_gateway
deploy/open_im_msg_transfer
deploy/open_im_push
deploy/open_im_timer_task
deploy/open_im_rpc_user
deploy/open_im_rpc_friend
deploy/open_im_rpc_group

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -8,19 +8,16 @@ import (
"Open_IM/internal/api/group"
"Open_IM/internal/api/manage"
apiChat "Open_IM/internal/api/msg"
"Open_IM/internal/api/office"
apiThird "Open_IM/internal/api/third"
"Open_IM/internal/api/user"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/middleware"
"Open_IM/pkg/common/tokenverify"
"Open_IM/pkg/getcdv3"
"Open_IM/pkg/utils"
"flag"
"fmt"
//_ "github.com/razeencheng/demo-go/swaggo-gin/docs"
"io"
"os"
"strconv"
@ -49,7 +46,6 @@ func main() {
// gin.SetMode(gin.DebugMode)
r := gin.New()
r.Use(gin.Recovery())
r.Use(utils.CorsHandler())
r.Use(middleware.GinParseOperationID)
log.Info("load config: ", config.Config)
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
@ -191,30 +187,7 @@ func main() {
conversationGroup.POST("/set_recv_msg_opt", conversation.SetRecvMsgOpt)
conversationGroup.POST("/modify_conversation_field", conversation.ModifyConversationField)
}
//// office
officeGroup := r.Group("/office")
{
officeGroup.POST("/get_user_tags", office.GetUserTags)
officeGroup.POST("/get_user_tag_by_id", office.GetUserTagByID)
officeGroup.POST("/create_tag", office.CreateTag)
officeGroup.POST("/delete_tag", office.DeleteTag)
officeGroup.POST("/set_tag", office.SetTag)
officeGroup.POST("/send_msg_to_tag", office.SendMsg2Tag)
officeGroup.POST("/get_send_tag_log", office.GetTagSendLogs)
officeGroup.POST("/create_one_work_moment", office.CreateOneWorkMoment)
officeGroup.POST("/delete_one_work_moment", office.DeleteOneWorkMoment)
officeGroup.POST("/like_one_work_moment", office.LikeOneWorkMoment)
officeGroup.POST("/comment_one_work_moment", office.CommentOneWorkMoment)
officeGroup.POST("/get_work_moment_by_id", office.GetWorkMomentByID)
officeGroup.POST("/get_user_work_moments", office.GetUserWorkMoments)
officeGroup.POST("/get_user_friend_work_moments", office.GetUserFriendWorkMoments)
officeGroup.POST("/set_user_work_moments_level", office.SetUserWorkMomentsLevel)
officeGroup.POST("/delete_comment", office.DeleteComment)
}
//
go rpc.RegisterConf()
go apiThird.MinioInit()
defaultPorts := config.Config.Api.GinPort
ginPort := flag.Int("port", defaultPorts[0], "get ginServerPort from cmd,default 10002 as port")

View File

@ -1,25 +0,0 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_cms_api
BIN_DIR=../../bin/
all: gotool build
build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s"
run:
@go run ./
gotool:
go fmt ./
go vet ./
install:
make build
mv ${BINARY_NAME} ${BIN_DIR}
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@ -1,30 +0,0 @@
package main
import (
"Open_IM/internal/cms_api"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/utils"
"flag"
"fmt"
"strconv"
"Open_IM/pkg/common/config"
"github.com/gin-gonic/gin"
)
func main() {
gin.SetMode(gin.ReleaseMode)
router := cmsapi.NewGinRouter()
router.Use(utils.CorsHandler())
defaultPorts := config.Config.CmsApi.GinPort
ginPort := flag.Int("port", defaultPorts[0], "get ginServerPort from cmd,default 10006 as port")
flag.Parse()
address := "0.0.0.0:" + strconv.Itoa(*ginPort)
if config.Config.Api.ListenIP != "" {
address = config.Config.Api.ListenIP + ":" + strconv.Itoa(*ginPort)
}
address = config.Config.CmsApi.ListenIP + ":" + strconv.Itoa(*ginPort)
fmt.Println("start cms api server, address: ", address, ", OpenIM version: ", constant.CurrentVersion, "\n")
router.Run(address)
}

View File

@ -1,23 +0,0 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_admin_cms
BIN_DIR=../../../bin/
all: gotool build
build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s"
run:
@go run ./
gotool:
go fmt ./
go vet ./
install:
make build
mv ${BINARY_NAME} ${BIN_DIR}
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@ -1,26 +0,0 @@
package main
import (
rpcMessageCMS "Open_IM/internal/rpc/admin_cms"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
promePkg "Open_IM/pkg/common/prometheus"
"flag"
"fmt"
)
func main() {
defaultPorts := config.Config.RpcPort.OpenImAdminCmsPort
rpcPort := flag.Int("port", defaultPorts[0], "rpc listening port")
prometheusPort := flag.Int("prometheus_port", config.Config.Prometheus.AdminCmsPrometheusPort[0], "adminCMSPrometheusPort default listen port")
flag.Parse()
fmt.Println("start cms rpc server, port: ", *rpcPort, ", OpenIM version: ", constant.CurrentVersion, "\n")
rpcServer := rpcMessageCMS.NewAdminCMSServer(*rpcPort)
go func() {
err := promePkg.StartPromeSrv(*prometheusPort)
if err != nil {
panic(err)
}
}()
rpcServer.Run()
}

View File

@ -1,23 +0,0 @@
.PHONY: all build run gotool install clean help
BINARY_NAME=open_im_office
BIN_DIR=../../../bin/
all: gotool build
build:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-w -s"
run:
@go run ./
gotool:
go fmt ./
go vet ./
install:
make build
mv ${BINARY_NAME} ${BIN_DIR}
clean:
@if [ -f ${BINARY_NAME} ] ; then rm ${BINARY_NAME} ; fi

View File

@ -1,26 +0,0 @@
package main
import (
rpc "Open_IM/internal/rpc/office"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
promePkg "Open_IM/pkg/common/prometheus"
"flag"
"fmt"
)
func main() {
defaultPorts := config.Config.RpcPort.OpenImOfficePort
rpcPort := flag.Int("port", defaultPorts[0], "rpc listening port")
prometheusPort := flag.Int("prometheus_port", config.Config.Prometheus.OfficePrometheusPort[0], "officePrometheusPort default listen port")
flag.Parse()
fmt.Println("start office rpc server, port: ", *rpcPort, ", OpenIM version: ", constant.CurrentVersion, "\n")
rpcServer := rpc.NewOfficeServer(*rpcPort)
go func() {
err := promePkg.StartPromeSrv(*prometheusPort)
if err != nil {
panic(err)
}
}()
rpcServer.Run()
}

View File

@ -1,5 +1,4 @@
# The class cannot be named by Pascal or camel case.
# The class cannot be named by Pascal or camel case.
# If it is not used, the corresponding structure will not be set,
# and it will not be read naturally.
serverversion: 2.3.7
@ -78,7 +77,6 @@ kafka:
# automatically obtain the machine's valid network card ip as the service ip,
# otherwise the configuration ip is preferred
#如果是单机模式用0.0.0.0或者不填,默认即可
serverip: 0.0.0.0
#作为rpc时注册到etcd的地址单机默认即可如果是集群部署需要修改具体使用内网地址还是外网地址要依情况而定目的是api/gateway能访问到
rpcRegisterIP:
@ -88,7 +86,6 @@ listenIP: 0.0.0.0
# endpoints 内部组件间访问的端点host名称访问时可以内部直接访问 host:port 来访问
endpoints:
api: openim_api
cmsapi: openim_cms_api
push: openim_push
msg_gateway: openim_msg_gateway
rpc_auth: openim_rpc_auth
@ -96,15 +93,11 @@ endpoints:
rpc_group: openim_rpc_group
rpc_msg: openim_rpc_msg
rpc_user: openim_rpc_user
rpc_admin_cms: openim_rpc_admin_cms
rpc_office: openim_rpc_office
api:
openImApiPort: [ 10002 ] #api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
cmsapi:
openImCmsApiPort: [ 10006 ] #管理后台api服务端口默认即可需要开放此端口或做nginx转发
listenIP: 0.0.0.0
sdk:
openImSdkWsPort: [ 10003 ] #jssdk服务端口默认即可项目中使用jssdk才需开放此端口或做nginx转发
dataDir: [ ../db/sdk/ ]
@ -159,20 +152,9 @@ rpcport: #rpc服务端口 默认即可
openImGroupPort: [ 10150 ]
openImAuthPort: [ 10160 ]
openImPushPort: [ 10170 ]
openImAdminCmsPort: [ 10200 ]
openImOfficePort: [ 10210 ]
openImConversationPort: [ 10230 ]
openImCachePort: [ 10240 ]
openImRealTimeCommPort: [ 11300 ]
c2c:
callbackBeforeSendMsg:
switch: false
timeoutStrategy: 1 #1:send
callbackAfterSendMsg:
switch: false
state:
stateChange:
switch: false
rpcregistername: #rpc注册服务名默认即可
openImUserName: User
@ -182,10 +164,9 @@ rpcregistername: #rpc注册服务名默认即可
openImRelayName: Relay
openImGroupName: Group
openImAuthName: Auth
openImAdminCMSName: AdminCMS
openImOfficeName: Office
openImConversationName: Conversation
openImRealTimeCommName: RealTimeComm
log:
storageLocation: ../logs/
rotationTime: 24
@ -274,15 +255,6 @@ tokenpolicy:
messageverify:
friendVerify:
# c2c:
# callbackBeforeSendMsg:
# switch: false
# timeoutStrategy: 1 #1:send
# callbackAfterSendMsg:
# switch: false
# state:
# stateChange:
# switch: false
#ios系统推送声音以及标记计数
iospush:
pushSound: "xxx"
@ -353,424 +325,6 @@ callback:
callbackTimeOut: 2
callbackFailedContinue: true # 回调超时是否继续
notification:
groupCreated:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "create group title" # xx create the group
desc: "create group desc"
ext: "create group ext"
defaultTips:
tips: "create the group" # xx create the group
groupInfoSet:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupInfoSet title"
desc: "groupInfoSet desc"
ext: "groupInfoSet ext"
defaultTips:
tips: "modified the group profile" # group info changed by xx
joinGroupApplication:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "joinGroupApplication title"
desc: "joinGroupApplication desc"
ext: "joinGroupApplication ext"
defaultTips:
tips: "apply to join the group" # group info changed by xx
memberQuit:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberQuit title"
desc: "memberQuit desc"
ext: "memberQuit ext"
defaultTips:
tips: "quit group msg" # group info changed by xx
groupApplicationAccepted:
conversation:
reliabilityLevel: 2
unreadCount: true
offlinePush:
switch: false
title: "groupApplicationAccepted title"
desc: "groupApplicationAccepted desc"
ext: "groupApplicationAccepted ext"
defaultTips:
tips: "was allowed to join the group" # group info changed by xx
groupApplicationRejected:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: " title"
desc: " desc"
ext: " ext"
defaultTips:
tips: "was rejected into the group" # group info changed by xx
groupOwnerTransferred:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupOwnerTransferred title"
desc: "groupOwnerTransferred desc"
ext: "groupOwnerTransferred ext"
defaultTips:
tips: "become a new group owner" # group info changed by xx
memberKicked:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberKicked title"
desc: "memberKicked desc"
ext: "memberKicked ext"
defaultTips:
tips: "was kicked out of the group" # group info changed by xx
memberInvited:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberInvited title"
desc: "memberInvited desc"
ext: "memberInvited ext"
defaultTips:
tips: "was invited into the group" # group info changed by xx
memberEnter:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberEnter title"
desc: "memberEnter desc"
ext: "memberEnter ext"
defaultTips:
tips: "entered the group" # group info changed by xx
groupDismissed:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupDismissed title"
desc: "groupDismissed desc"
ext: "groupDismissed ext"
defaultTips:
tips: "group dismissed"
groupMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMuted title"
desc: "groupMuted desc"
ext: "groupMuted ext"
defaultTips:
tips: "group Muted"
groupCancelMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupCancelMuted title"
desc: "groupCancelMuted desc"
ext: "groupCancelMuted ext"
defaultTips:
tips: "group Cancel Muted"
groupMemberMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMemberMuted title"
desc: "groupMemberMuted desc"
ext: "groupMemberMuted ext"
defaultTips:
tips: "group Member Muted"
groupMemberCancelMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMemberCancelMuted title"
desc: "groupMemberCancelMuted desc"
ext: "groupMemberCancelMuted ext"
defaultTips:
tips: "group Member Cancel Muted"
groupMemberInfoSet:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "groupMemberInfoSet title"
desc: "groupMemberInfoSet desc"
ext: "groupMemberInfoSet ext"
defaultTips:
tips: "group member info set"
#############################friend#################################
friendApplicationAdded:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Somebody applies to add you as a friend"
desc: "Somebody applies to add you as a friend"
ext: "Somebody applies to add you as a friend"
defaultTips:
tips: "I applies to add you as a friend" #
friendApplicationApproved:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Someone applies to add your friend application"
desc: "Someone applies to add your friend application"
ext: "Someone applies to add your friend application"
defaultTips:
tips: "I applies to add your friend application" #
friendApplicationRejected:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Someone rejected your friend application"
desc: "Someone rejected your friend application"
ext: "Someone rejected your friend application"
defaultTips:
tips: "I rejected your friend application" #
friendAdded:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "We have become friends"
desc: "We have become friends"
ext: "We have become friends"
defaultTips:
tips: "We have become friends" #
friendDeleted:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "deleted a friend"
desc: "deleted a friend"
ext: "deleted a friend"
defaultTips:
tips: "deleted a friend" #
friendRemarkSet:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Your friend's profile has been changed"
desc: "Your friend's profile has been changed"
ext: "Your friend's profile has been changed"
defaultTips:
tips: "Your friend's profile has been changed" #
blackAdded:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "blocked a user"
desc: "blocked a user"
ext: "blocked a user"
defaultTips:
tips: "blocked a user" #
blackDeleted:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
defaultTips:
tips: "Remove a blocked user"
friendInfoUpdated:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "friend info updated"
desc: "friend info updated"
ext: "friend info updated"
defaultTips:
tips: "friend info updated"
#####################user#########################
userInfoUpdated:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
defaultTips:
tips: "remove a blocked user"
#####################conversation#########################
conversationOptUpdate:
conversation:
reliabilityLevel: 1
unreadCount: false
offlinePush:
switch: true
title: "conversation opt update"
desc: "conversation opt update"
ext: "conversation opt update"
defaultTips:
tips: "conversation opt update"
conversationSetPrivate:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "burn after reading"
desc: "burn after reading"
ext: "burn after reading"
defaultTips:
openTips: "burn after reading was opened"
closeTips: "burn after reading was closed"
###################workMoments################
workMomentsNotification:
conversation:
reliabilityLevel: 2
unreadCount: true
offlinePush:
switch: true
title: "burn after reading"
desc: "burn after reading"
ext: "burn after reading"
defaultTips:
openTips: "burn after reading was opened"
closeTips: "burn after reading was closed"
#---------------demo configuration---------------------#
#The following configuration items are applied to openIM Demo configuration
#是否启动demo如果自身没有账号体系设置为true
demoswitch: true
demo:
listenIP: 0.0.0.0
#demo对外服务端口默认即可需要开放此端口或做nginx转发
openImDemoPort: [ 10004 ]
alismsverify: #阿里云短信配置在阿里云申请成功后修改以下四项enable为true则必须修改阿里云为默认短信验证方式
accessKeyId:
accessKeySecret:
signName:
verificationCodeTemplateCode:
enable: false
tencentsms: #腾讯云短信配置在腾讯云申请成功后修改以下选项enable为true则必须修改
appID:
region:
secretID:
secretKey:
signName:
verificationCodeTemplateCode:
enable: true
superCode: 666666 #超级验证码,建议修改掉,收不到短信验证码时可以用此替代
needInvitationCode: false
# second
codeTTL: 60
useSuperCode: true
mail: #仅支持qq邮箱具体操作参考 https://service.mail.qq.com/cgi-bin/help?subtype=1&id=28&no=1001256 必须修改
title:
senderMail:
senderAuthorizationCode:
smtpAddr:
smtpPort: #需开放此端口 出口方向
testDepartMentID: 001
imAPIURL: http://127.0.0.1:10002
onboardProcess: false # 是否开启注册流程
joinDepartmentIDList: [] # 用户注册进来默认加的部门ID列表 不填就随机
joinDepartmentGroups: false # 注册是否加部门群
oaNotification: false # 注册是否发送OA通知
workMoment:
onlyFriendCanSee: false
rtc:
signalTimeout: 35
@ -784,9 +338,6 @@ prometheus:
groupPrometheusPort: [ 20150 ]
authPrometheusPort: [ 20160 ]
pushPrometheusPort: [ 20170 ]
adminCmsPrometheusPort: [ 20200 ]
officePrometheusPort: [ 20210 ]
conversationPrometheusPort: [ 20230 ]
cachePrometheusPort: [ 20240 ]
realTimeCommPrometheusPort: [ 21300 ]
messageTransferPrometheusPort: [ 21400, 21401, 21402, 21403 ] # 端口数量和 script/path_info.cfg msg_transfer_service_num保持一致

359
config/notification.yaml Normal file
View File

@ -0,0 +1,359 @@
notification:
groupCreated:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "create group title" # xx create the group
desc: "create group desc"
ext: "create group ext"
defaultTips:
tips: "create the group" # xx create the group
groupInfoSet:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupInfoSet title"
desc: "groupInfoSet desc"
ext: "groupInfoSet ext"
defaultTips:
tips: "modified the group profile" # group info changed by xx
joinGroupApplication:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "joinGroupApplication title"
desc: "joinGroupApplication desc"
ext: "joinGroupApplication ext"
defaultTips:
tips: "apply to join the group" # group info changed by xx
memberQuit:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberQuit title"
desc: "memberQuit desc"
ext: "memberQuit ext"
defaultTips:
tips: "quit group msg" # group info changed by xx
groupApplicationAccepted:
conversation:
reliabilityLevel: 2
unreadCount: true
offlinePush:
switch: false
title: "groupApplicationAccepted title"
desc: "groupApplicationAccepted desc"
ext: "groupApplicationAccepted ext"
defaultTips:
tips: "was allowed to join the group" # group info changed by xx
groupApplicationRejected:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: " title"
desc: " desc"
ext: " ext"
defaultTips:
tips: "was rejected into the group" # group info changed by xx
groupOwnerTransferred:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupOwnerTransferred title"
desc: "groupOwnerTransferred desc"
ext: "groupOwnerTransferred ext"
defaultTips:
tips: "become a new group owner" # group info changed by xx
memberKicked:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberKicked title"
desc: "memberKicked desc"
ext: "memberKicked ext"
defaultTips:
tips: "was kicked out of the group" # group info changed by xx
memberInvited:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberInvited title"
desc: "memberInvited desc"
ext: "memberInvited ext"
defaultTips:
tips: "was invited into the group" # group info changed by xx
memberEnter:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "memberEnter title"
desc: "memberEnter desc"
ext: "memberEnter ext"
defaultTips:
tips: "entered the group" # group info changed by xx
groupDismissed:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupDismissed title"
desc: "groupDismissed desc"
ext: "groupDismissed ext"
defaultTips:
tips: "group dismissed"
groupMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMuted title"
desc: "groupMuted desc"
ext: "groupMuted ext"
defaultTips:
tips: "group Muted"
groupCancelMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupCancelMuted title"
desc: "groupCancelMuted desc"
ext: "groupCancelMuted ext"
defaultTips:
tips: "group Cancel Muted"
groupMemberMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMemberMuted title"
desc: "groupMemberMuted desc"
ext: "groupMemberMuted ext"
defaultTips:
tips: "group Member Muted"
groupMemberCancelMuted:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: false
title: "groupMemberCancelMuted title"
desc: "groupMemberCancelMuted desc"
ext: "groupMemberCancelMuted ext"
defaultTips:
tips: "group Member Cancel Muted"
groupMemberInfoSet:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: false
title: "groupMemberInfoSet title"
desc: "groupMemberInfoSet desc"
ext: "groupMemberInfoSet ext"
defaultTips:
tips: "group member info set"
#############################friend#################################
friendApplicationAdded:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Somebody applies to add you as a friend"
desc: "Somebody applies to add you as a friend"
ext: "Somebody applies to add you as a friend"
defaultTips:
tips: "I applies to add you as a friend" #
friendApplicationApproved:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Someone applies to add your friend application"
desc: "Someone applies to add your friend application"
ext: "Someone applies to add your friend application"
defaultTips:
tips: "I applies to add your friend application" #
friendApplicationRejected:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Someone rejected your friend application"
desc: "Someone rejected your friend application"
ext: "Someone rejected your friend application"
defaultTips:
tips: "I rejected your friend application" #
friendAdded:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "We have become friends"
desc: "We have become friends"
ext: "We have become friends"
defaultTips:
tips: "We have become friends" #
friendDeleted:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "deleted a friend"
desc: "deleted a friend"
ext: "deleted a friend"
defaultTips:
tips: "deleted a friend" #
friendRemarkSet:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Your friend's profile has been changed"
desc: "Your friend's profile has been changed"
ext: "Your friend's profile has been changed"
defaultTips:
tips: "Your friend's profile has been changed" #
blackAdded:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "blocked a user"
desc: "blocked a user"
ext: "blocked a user"
defaultTips:
tips: "blocked a user" #
blackDeleted:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
defaultTips:
tips: "Remove a blocked user"
friendInfoUpdated:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "friend info updated"
desc: "friend info updated"
ext: "friend info updated"
defaultTips:
tips: "friend info updated"
#####################user#########################
userInfoUpdated:
conversation:
reliabilityLevel: 2
unreadCount: false
offlinePush:
switch: true
title: "Remove a blocked user"
desc: "Remove a blocked user"
ext: "Remove a blocked user"
defaultTips:
tips: "remove a blocked user"
#####################conversation#########################
conversationOptUpdate:
conversation:
reliabilityLevel: 1
unreadCount: false
offlinePush:
switch: true
title: "conversation opt update"
desc: "conversation opt update"
ext: "conversation opt update"
defaultTips:
tips: "conversation opt update"
conversationSetPrivate:
conversation:
reliabilityLevel: 3
unreadCount: true
offlinePush:
switch: true
title: "burn after reading"
desc: "burn after reading"
ext: "burn after reading"
defaultTips:
openTips: "burn after reading was opened"
closeTips: "burn after reading was closed"

View File

@ -7,9 +7,6 @@ upstream im_api{
upstream im_jssdk_gateway{
server 127.0.0.1:10003; #IM jssdk服务器地址 根据部署情况可指定多台
}
upstream im_demo{
server 127.0.0.1:10004; #IM demo登录注册服务器地址 根据部署情况可指定多台
}
upstream storage {
server 127.0.0.1:10005; #MinIO服务器地址 暂时支持1台
}
@ -83,14 +80,6 @@ server {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_jssdk_gateway/;
}
location ^~/demo/ { # 10004 demo
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://im_demo/;
}
location ^~/admin/ { #10006 admin
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;

View File

@ -1,20 +0,0 @@
FROM ubuntu
# 设置固定的项目路径
ENV WORKDIR /Open-IM-Server
ENV CMDDIR $WORKDIR/cmd
ENV CONFIG_NAME $WORKDIR/config/config.yaml
# 将可执行文件复制到目标目录
ADD ./open_im_admin_cms $WORKDIR/cmd/main
# 创建用于挂载的几个目录,添加可执行权限
RUN mkdir $WORKDIR/logs $WORKDIR/config $WORKDIR/script && \
chmod +x $WORKDIR/cmd/main
VOLUME ["/Open-IM-Server/logs","/Open-IM-Server/config", "/Open-IM-Server/script"]
WORKDIR $CMDDIR
CMD ./main

View File

@ -1,43 +0,0 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: admin-cms-deployment
spec:
selector:
matchLabels:
app: admin-cms # 选择这个指定标签执行
replicas: 1 # 运行pod数量
template:
metadata:
labels:
app: admin-cms # 标签
spec:
containers:
- name: admin-cms
image: openim/admin_cms:v2.3.4
# imagePullPolicy: Always #每次启动都重新拉取镜像
ports:
- containerPort: 10200
volumeMounts:
- name: config
mountPath: /Open-IM-Server/config
readOnly: true
- name: usualConfig
mountPath: /Open-IM-Server/config
readOnly: true
env:
- name: CONFIG_NAME
value: "/Open-IM-Server"
- name: USUAL_CONFIG_NAME
value: "/Open-IM-Server"
volumes:
- name: config
configMap:
name: openim-config
- name: usualConfig
configMap:
name: openim-usualConfig
strategy: #更新策略
type: RollingUpdate # 滚动更新

View File

@ -1,18 +0,0 @@
FROM ubuntu
# 设置固定的项目路径
ENV WORKDIR /Open-IM-Server
ENV CMDDIR $WORKDIR/cmd
ENV CONFIG_NAME $WORKDIR/config/config.yaml
# 将可执行文件复制到目标目录
ADD ./open_im_cms_api $WORKDIR/cmd/main
# 创建用于挂载的几个目录,添加可执行权限
RUN mkdir $WORKDIR/logs $WORKDIR/config $WORKDIR/script && \
chmod +x $WORKDIR/cmd/main
VOLUME ["/Open-IM-Server/logs","/Open-IM-Server/config","/Open-IM-Server/script"]
WORKDIR $CMDDIR
CMD ./main

View File

@ -1,56 +0,0 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: cms-api-deployment
spec:
selector:
matchLabels:
app: cms-api # 选择这个指定标签执行
replicas: 1 # 运行pod数量
template:
metadata:
labels:
app: cms-api # 标签
spec:
containers:
- name: cms-api
image: openim/cms_api:v2.3.4
imagePullPolicy: Always
ports:
- containerPort: 10006
volumeMounts:
- name: config
mountPath: /Open-IM-Server/config
readOnly: true
- name: usualConfig
mountPath: /Open-IM-Server/config
readOnly: true
env:
- name: CONFIG_NAME
value: "/Open-IM-Server"
- name: USUAL_CONFIG_NAME
value: "/Open-IM-Server"
volumes:
- name: config
configMap:
name: openim-config
- name: usualConfig
configMap:
name: openim-usualConfig
strategy: #更新策略
type: RollingUpdate # 滚动更新
---
apiVersion: v1
kind: Service
metadata:
name: cms-api
spec:
ports:
- name: cms-api-port
protocol: TCP
port: 10006
targetPort: 10006
selector:
app: cms-api
type: NodePort

View File

@ -1,28 +1,6 @@
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/proxy-http-version: "1.1"
nginx.ingress.kubernetes.io/proxy-read-timeout: "3600"
nginx.ingress.kubernetes.io/proxy-send-timeout: "3600"
name: sdk-server-ingress
spec:
rules:
- host: sdk-server.openim.xxx.com
http:
paths:
- backend:
service:
name: sdk-server
port:
number: 10003
path: /
pathType: Prefix
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
@ -67,53 +45,3 @@ spec:
number: 10002
path: /
pathType: Prefix
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/Access-Control-Allow-Origin: '*'
nginx.ingress.kubernetes.io/cors-allow-headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-auth-token,Pagination
nginx.ingress.kubernetes.io/cors-allow-methods: 'PUT, GET, POST, OPTIONS'
nginx.ingress.kubernetes.io/cors-allow-origin: '*'
nginx.ingress.kubernetes.io/enable-cors: 'true'
nginx.ingress.kubernetes.io/service-weight: ''
name: demo-ingress
spec:
rules:
- host: demo.openim.xxx.com
http:
paths:
- backend:
service:
name: demo
port:
number: 10004
path: /
pathType: Prefix
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/Access-Control-Allow-Origin: '*'
nginx.ingress.kubernetes.io/cors-allow-headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,x-auth-token,Pagination
nginx.ingress.kubernetes.io/cors-allow-methods: 'PUT, GET, POST, OPTIONS'
nginx.ingress.kubernetes.io/cors-allow-origin: '*'
nginx.ingress.kubernetes.io/enable-cors: 'true'
nginx.ingress.kubernetes.io/service-weight: ''
name: cms-api-ingress
spec:
rules:
- host: cms-api.openim.xxx.com
http:
paths:
- backend:
service:
name: cms-api
port:
number: 10006
path: /
pathType: Prefix

View File

@ -9,8 +9,7 @@
6. 将rpcRegisterIP修改为空, 此地址为每个rpc注册到ETCD的地址, 置空每个rpc将会将pod地址注册到ETCD, 才能正确rpc请求(重要)
7. 如果使用minio作为对象存储, 还需要修改minio的地址
8. 其他如果使用离线推送,需要修改push离线推送配置
9. 修改demo中的imAPIURL字段为openIM api的ingress或者service地址, 需要让demo的pod能正确请求到(重要)
10. 其他非必须配置修改, 如短信,推送等
9. 其他非必须配置修改, 如短信,推送等
### 2. 项目根目录创建im configMap到k8s openim namespace
1. 为open-IM项目创建单独命名空间
@ -75,8 +74,6 @@ kubectl 启动所有deployment, services, ingress
telnet msg-gateway.openim.xxx.com {{your_ingress_port}}
telnet sdk-server.openim.xxx.com {{your_ingress_port}}
telnet api.openim.xxx.com {{your_ingress_port}}
telnet cms-api.openim.xxx.com {{your_ingress_port}}
telnet demo.openim.xxx.com {{your_ingress_port}}
```
#### openIM k8s更新

View File

@ -3,23 +3,16 @@
service=(
#api service file
api
cms-api
#rpc service file
user
friend
group
auth
admin-cms
office
organization
conversation
cache
msg-gateway
msg-transfer
msg
push
sdk-server
demo
)
for i in ${service[*]}
@ -28,9 +21,6 @@ do
done
kubectl -n openim delete service api
kubectl -n openim delete service cms-api
kubectl -n openim delete service sdk-server
kubectl -n openim delete service msg-gateway
kubectl -n openim delete service demo
echo done

View File

@ -1,42 +0,0 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: office-deployment
spec:
selector:
matchLabels:
app: office # 选择这个指定标签执行
replicas: 1 # 运行pod数量
template:
metadata:
labels:
app: office # 标签
spec:
containers:
- name: office
image: openim/office:v2.3.4
# imagePullPolicy: Always
ports:
- containerPort: 10210
volumeMounts:
- name: config
mountPath: /Open-IM-Server/config
readOnly: true
- name: usualConfig
mountPath: /Open-IM-Server/config
readOnly: true
env:
- name: CONFIG_NAME
value: "/Open-IM-Server"
- name: USUAL_CONFIG_NAME
value: "/Open-IM-Server"
volumes:
- name: config
configMap:
name: openim-config
- name: usualConfig
configMap:
name: openim-usualConfig
strategy: #更新策略
type: RollingUpdate # 滚动更新

View File

@ -1,20 +0,0 @@
FROM ubuntu
# 设置固定的项目路径
ENV WORKDIR /Open-IM-Server
ENV CMDDIR $WORKDIR/cmd
ENV CONFIG_NAME $WORKDIR/config/config.yaml
# 将可执行文件复制到目标目录
ADD ./open_im_office $WORKDIR/cmd/main
# 创建用于挂载的几个目录,添加可执行权限
RUN mkdir $WORKDIR/logs $WORKDIR/config $WORKDIR/script && \
chmod +x $WORKDIR/cmd/main
VOLUME ["/Open-IM-Server/logs","/Open-IM-Server/config","/Open-IM-Server/script"]
WORKDIR $CMDDIR
CMD ./main

View File

@ -2,18 +2,14 @@
service=(
#api service file
api
cmsapi
#rpc service file
user
friend
group
auth
admincms
office
conversation
msggateway
msgtransfer
msg
push
sdkserver
)

View File

@ -1,57 +0,0 @@
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: sdk-server-deployment
spec:
selector:
matchLabels:
app: sdk-server # 选择这个指定标签执行
replicas: 1 # 运行pod数量
template:
metadata:
labels:
app: sdk-server # 标签
spec:
containers:
- name: sdk-server
image: openim/sdk_server:v2.3.4
# imagePullPolicy: Always
ports:
- containerPort: 10003
volumeMounts:
- name: config
mountPath: /Open-IM-Server/config
readOnly: true
- name: local-db
mountPath: /db/sdk
env:
- name: CONFIG_NAME
value: "/Open-IM-Server"
command: ["/Open-IM-Server/main"]
args: ["-openIM_ws_address", "ws_addr", "-sdkws_port", "10003", "-openIM_api_address", "api_address", "-openIM_log_level", "6"]
volumes:
- name: config
configMap:
name: openim-config
- name: local-db
hostPath:
path: /db/sdk
strategy: #更新策略
type: RollingUpdate # 滚动更新
---
apiVersion: v1
kind: Service
metadata:
name: sdk-server
spec:
ports:
- name: sdk-server-port
protocol: TCP
port: 10003
targetPort: 10003
selector:
app: sdk-server
type: NodePort

View File

@ -1,18 +0,0 @@
FROM ubuntu
# 设置固定的项目路径
ENV WORKDIR /Open-IM-Server
ENV CMDDIR $WORKDIR/cmd
ENV CONFIG_NAME $WORKDIR/config/config.yaml
# 将可执行文件复制到目标目录
ADD ./open_im_sdk_server $WORKDIR/main
# 创建用于挂载的几个目录,添加可执行权限
RUN mkdir $WORKDIR/logs $WORKDIR/config $WORKDIR/db && \
chmod +x $WORKDIR/main
VOLUME ["/Open-IM-Server/logs","/Open-IM-Server/config","/Open-IM-Server/script","/Open-IM-Server/db/sdk"]
WORKDIR $CMDDIR
CMD ./main

View File

@ -17,11 +17,6 @@ scrape_configs:
labels:
group: 'api'
- targets: ['localhost:10006']
labels:
group: 'cms-api'
- targets: ['localhost:20110']
labels:
group: 'user'
@ -52,27 +47,13 @@ scrape_configs:
- targets: ['localhost:20120']
labels:
group: 'friend'
group: 'friend'
- targets: ['localhost:20200']
labels:
group: 'admin-cms'
- targets: ['localhost:20120']
labels:
group: 'office'
- targets: ['localhost:20220']
labels:
group: 'organization'
- targets: ['localhost:20230']
labels:
group: 'conversation'
- targets: ['localhost:20240']
labels:
group: 'cache'
- targets: ['localhost:21400', 'localhost:21401', 'localhost:21402', 'localhost:21403']
labels:

View File

@ -7,7 +7,7 @@ import (
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tokenverify"
rpc "Open_IM/pkg/proto/auth"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
@ -43,7 +43,7 @@ func UserRegister(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 401, "errMsg": errMsg})
return
}
req := &rpc.UserRegisterReq{UserInfo: &open_im_sdk.UserInfo{}}
req := &rpc.UserRegisterReq{UserInfo: &sdkws.UserInfo{}}
utils.CopyStructFields(req.UserInfo, &params)
//copier.Copy(req.UserInfo, &params)
req.OperationID = params.OperationID

View File

@ -8,7 +8,7 @@ package friend
// "Open_IM/pkg/common/tokenverify"
// "Open_IM/pkg/getcdv3"
// rpc "Open_IM/pkg/proto/friend"
// open_im_sdk "Open_IM/pkg/proto/sdkws"
// sdkws "Open_IM/pkg/proto/sdkws"
// "Open_IM/pkg/utils"
// "context"
// "github.com/gin-gonic/gin"
@ -296,7 +296,7 @@ package friend
//// @Param token header string true "im token"
//// @Param req body api.GetBlackListReq true "fromUserID要获取黑名单的用户"
//// @Produce json
//// @Success 0 {object} api.GetBlackListResp{data=[]open_im_sdk.PublicUserInfo}
//// @Success 0 {object} api.GetBlackListResp{data=[]sdkws.PublicUserInfo}
//// @Failure 500 {object} api.Swagger400Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger500Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /friend/get_black_list [post]
@ -339,7 +339,7 @@ package friend
//
// resp := api.GetBlackListResp{CommResp: api.CommResp{ErrCode: RpcResp.CommonResp.ErrCode, ErrMsg: RpcResp.CommonResp.ErrMsg}}
// for _, v := range RpcResp.BlackUserInfoList {
// black := open_im_sdk.PublicUserInfo{}
// black := sdkws.PublicUserInfo{}
// utils.CopyStructFields(&black, v)
// resp.BlackUserInfoList = append(resp.BlackUserInfoList, &black)
// }
@ -519,7 +519,7 @@ package friend
//// @Param token header string true "im token"
//// @Param req body api.GetFriendListReq true "fromUserID为要获取好友列表的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetFriendListResp{data=[]open_im_sdk.FriendInfo}
//// @Success 0 {object} api.GetFriendListResp{data=[]sdkws.FriendInfo}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /friend/get_friend_list [post]
@ -575,7 +575,7 @@ package friend
//// @Param token header string true "im token"
//// @Param req body api.GetFriendApplyListReq true "fromUserID为要获取申请列表的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetFriendApplyListResp{data=[]open_im_sdk.FriendRequest}
//// @Success 0 {object} api.GetFriendApplyListResp{data=[]sdkws.FriendRequest}
//// @Failure 500 {object} api.Swagger400Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /friend/get_friend_apply_list [post]
@ -631,7 +631,7 @@ package friend
//// @Param token header string true "im token"
//// @Param req body api.GetSelfApplyListReq true "fromUserID为自己的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetSelfApplyListResp{data=[]open_im_sdk.FriendRequest}
//// @Success 0 {object} api.GetSelfApplyListResp{data=[]sdkws.FriendRequest}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /friend/get_self_friend_apply_list [post]

View File

@ -99,7 +99,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.GetGroupMembersInfoReq true "groupID为要获取的群ID <br> memberList为要获取群成员的群ID列表"
//// @Produce json
//// @Success 0 {object} api.GetGroupMembersInfoResp{data=[]open_im_sdk.GroupMemberFullInfo}
//// @Success 0 {object} api.GetGroupMembersInfoResp{data=[]sdkws.GroupMemberFullInfo}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/get_group_members_info [post]
@ -200,7 +200,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.GetGroupAllMemberReq true "GroupID为要获取群成员的群ID"
//// @Produce json
//// @Success 0 {object} api.GetGroupAllMemberResp{data=[]open_im_sdk.GroupMemberFullInfo}
//// @Success 0 {object} api.GetGroupAllMemberResp{data=[]sdkws.GroupMemberFullInfo}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/get_group_all_member_list [post]
@ -256,7 +256,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.GetJoinedGroupListReq true "fromUserID为要获取的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetJoinedGroupListResp{data=[]open_im_sdk.GroupInfo}
//// @Success 0 {object} api.GetJoinedGroupListResp{data=[]sdkws.GroupInfo}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/get_joined_group_list [post]
@ -379,7 +379,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.CreateGroupReq true "groupType这里填0代表普通群 <br>groupName为群名称<br> introduction为群介绍<br> notification为群公共<br>ownerUserID为群主ID <br> ex为群扩展字段 <br> memberList中对象roleLevel为群员角色,1为普通用户 2为群主 3为管理员"
//// @Produce json
//// @Success 0 {object} api.CreateGroupResp{data=open_im_sdk.GroupInfo}
//// @Success 0 {object} api.CreateGroupResp{data=sdkws.GroupInfo}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/create_group [post]
@ -397,7 +397,7 @@ package group
//// c.JSON(http.StatusOK, gin.H{"errCode": 400, "errMsg": errMsg})
//// return
//// }
//// req := &rpc.CreateGroupReq{GroupInfo: &open_im_sdk.GroupInfo{}}
//// req := &rpc.CreateGroupReq{GroupInfo: &sdkws.GroupInfo{}}
//// utils.CopyStructFields(req.GroupInfo, &params)
////
//// for _, v := range params.MemberList {
@ -456,7 +456,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.GetGroupApplicationListReq true "fromUserID为要获取的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetGroupApplicationListResp{data=[]open_im_sdk.GroupRequest}
//// @Success 0 {object} api.GetGroupApplicationListResp{data=[]sdkws.GroupRequest}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/get_recv_group_applicationList [post]
@ -509,7 +509,7 @@ package group
//// @Param token header string true "im token"
//// @Param req body api.GetUserReqGroupApplicationListReq true "userID为要获取的用户ID"
//// @Produce json
//// @Success 0 {object} api.GetGroupApplicationListResp{data=[]open_im_sdk.GroupRequest}
//// @Success 0 {object} api.GetGroupApplicationListResp{data=[]sdkws.GroupRequest}
//// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
//// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
//// @Router /group/get_user_req_group_applicationList [post]
@ -572,7 +572,7 @@ package group
// c.JSON(http.StatusOK, resp)
//}
//
////func transferGroupInfo(input []*open_im_sdk.GroupInfo) []*api.GroupInfoAlias {
////func transferGroupInfo(input []*sdkws.GroupInfo) []*api.GroupInfoAlias {
//// var result []*api.GroupInfoAlias
//// for _, v := range input {
//// t := &api.GroupInfoAlias{}
@ -766,7 +766,7 @@ package group
//// c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
//// return
//// }
//// req := &rpc.SetGroupInfoReq{GroupInfoForSet: &open_im_sdk.GroupInfoForSet{}}
//// req := &rpc.SetGroupInfoReq{GroupInfoForSet: &sdkws.GroupInfoForSet{}}
//// utils.CopyStructFields(req.GroupInfoForSet, &params)
//// req.OperationID = params.OperationID
//// argsHandle(&params, req)

View File

@ -14,7 +14,7 @@ import (
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tokenverify"
pbChat "Open_IM/pkg/proto/msg"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
@ -76,7 +76,7 @@ func newUserSendMsgReq(params *api.ManagementSendMsgReq) *pbChat.SendMsgReq {
pbData := pbChat.SendMsgReq{
OperationID: params.OperationID,
MsgData: &open_im_sdk.MsgData{
MsgData: &sdkws.MsgData{
SendID: params.SendID,
GroupID: params.GroupID,
ClientMsgID: utils.GetMsgID(params.SendID),
@ -95,7 +95,7 @@ func newUserSendMsgReq(params *api.ManagementSendMsgReq) *pbChat.SendMsgReq {
},
}
if params.ContentType == constant.OANotification {
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.JsonDetail = utils.StructToJsonString(params.Content)
pbData.MsgData.Content, err = proto.Marshal(&tips)
if err != nil {
@ -231,7 +231,7 @@ func ManagementSendMsg(c *gin.Context) {
}
log.Info(params.OperationID, "", "api ManagementSendMsg call end..., [data: %s] [reply: %s]", pbData.String(), RpcResp.String())
resp := api.ManagementSendMsgResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, ResultList: open_im_sdk.UserSendMsgResp{ServerMsgID: RpcResp.ServerMsgID, ClientMsgID: RpcResp.ClientMsgID, SendTime: RpcResp.SendTime}}
resp := api.ManagementSendMsgResp{CommResp: api.CommResp{ErrCode: RpcResp.ErrCode, ErrMsg: RpcResp.ErrMsg}, ResultList: sdkws.UserSendMsgResp{ServerMsgID: RpcResp.ServerMsgID, ClientMsgID: RpcResp.ClientMsgID, SendTime: RpcResp.SendTime}}
log.Info(params.OperationID, "ManagementSendMsg return", resp)
c.JSON(http.StatusOK, resp)
}

View File

@ -6,7 +6,7 @@ import (
"Open_IM/pkg/common/tokenverify"
"Open_IM/pkg/getcdv3"
"Open_IM/pkg/proto/msg"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
@ -46,7 +46,7 @@ func PullMsgBySeqList(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "token validate err"})
return
}
pbData := open_im_sdk.PullMessageBySeqListReq{}
pbData := sdkws.PullMessageBySeqListReq{}
pbData.UserID = params.SendID
pbData.OperationID = params.OperationID
pbData.SeqList = params.SeqList

View File

@ -4,7 +4,7 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
pbChat "Open_IM/pkg/proto/msg"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"context"
"Open_IM/pkg/getcdv3"
@ -20,17 +20,17 @@ type paramsUserSendMsg struct {
SenderFaceURL string `json:"senderFaceUrl"`
OperationID string `json:"operationID" binding:"required"`
Data struct {
SessionType int32 `json:"sessionType" binding:"required"`
MsgFrom int32 `json:"msgFrom" binding:"required"`
ContentType int32 `json:"contentType" binding:"required"`
RecvID string `json:"recvID" `
GroupID string `json:"groupID" `
ForceList []string `json:"forceList"`
Content []byte `json:"content" binding:"required"`
Options map[string]bool `json:"options" `
ClientMsgID string `json:"clientMsgID" binding:"required"`
CreateTime int64 `json:"createTime" binding:"required"`
OffLineInfo *open_im_sdk.OfflinePushInfo `json:"offlineInfo" `
SessionType int32 `json:"sessionType" binding:"required"`
MsgFrom int32 `json:"msgFrom" binding:"required"`
ContentType int32 `json:"contentType" binding:"required"`
RecvID string `json:"recvID" `
GroupID string `json:"groupID" `
ForceList []string `json:"forceList"`
Content []byte `json:"content" binding:"required"`
Options map[string]bool `json:"options" `
ClientMsgID string `json:"clientMsgID" binding:"required"`
CreateTime int64 `json:"createTime" binding:"required"`
OffLineInfo *sdkws.OfflinePushInfo `json:"offlineInfo" `
}
}
@ -38,7 +38,7 @@ func newUserSendMsgReq(token string, params *paramsUserSendMsg) *pbChat.SendMsgR
pbData := pbChat.SendMsgReq{
Token: token,
OperationID: params.OperationID,
MsgData: &open_im_sdk.MsgData{
MsgData: &sdkws.MsgData{
SendID: params.SendID,
RecvID: params.Data.RecvID,
GroupID: params.Data.GroupID,

View File

@ -1,450 +0,0 @@
package office
import (
api "Open_IM/pkg/api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tokenverify"
"Open_IM/pkg/getcdv3"
pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"google.golang.org/grpc"
"net/http"
"strings"
)
// @Summary 获取用户标签信息
// @Description 用户获取自己的所有的标签
// @Tags 标签
// @ID GetUserTags
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetUserTagsReq true "请求"
// @Produce json
// @Success 0 {object} api.GetUserTagsResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_user_tags [post]
func GetUserTags(c *gin.Context) {
var (
req api.GetUserTagsReq
resp api.GetUserTagsResp
reqPb pbOffice.GetUserTagsReq
respPb *pbOffice.GetUserTagsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserTags(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserTags rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
if respPb.Tags != nil {
resp.Data.Tags = respPb.Tags
} else {
resp.Data.Tags = []*pbOffice.Tag{}
}
c.JSON(http.StatusOK, resp)
}
// @Summary 创建标签
// @Description 创建标签
// @Tags 标签
// @ID CreateTag
// @Accept json
// @Param token header string true "im token"
// @Param req body api.CreateTagReq true "请求"
// @Produce json
// @Success 0 {object} api.CreateTagResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/create_tag [post]
func CreateTag(c *gin.Context) {
var (
req api.CreateTagReq
resp api.CreateTagResp
reqPb pbOffice.CreateTagReq
respPb *pbOffice.CreateTagResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.CreateTag(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateTag rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
c.JSON(http.StatusOK, resp)
}
// @Summary 删除标签
// @Description 根据标签ID创建标签
// @Tags 标签
// @ID DeleteTag
// @Accept json
// @Param token header string true "im token"
// @Param req body api.DeleteTagReq true "请求"
// @Produce json
// @Success 0 {object} api.DeleteTagResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/delete_tag [post]
func DeleteTag(c *gin.Context) {
var (
req api.DeleteTagReq
resp api.DeleteTagResp
reqPb pbOffice.DeleteTagReq
respPb *pbOffice.DeleteTagResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.DeleteTag(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateTag rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
c.JSON(http.StatusOK, resp)
}
// @Summary 修改标签
// @Description 根据标签ID修改标签用户列表, 名称
// @Tags 标签
// @ID SetTag
// @Accept json
// @Param token header string true "im token"
// @Param req body api.SetTagReq true "请求"
// @Produce json
// @Success 0 {object} api.SetTagResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/set_tag [post]
func SetTag(c *gin.Context) {
var (
req api.SetTagReq
resp api.SetTagResp
reqPb pbOffice.SetTagReq
respPb *pbOffice.SetTagResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.SetTag(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateTag rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
c.JSON(http.StatusOK, resp)
}
// @Summary 发送标签消息
// @Description 对标签用户发送消息
// @Tags 标签
// @ID SendMsg2Tag
// @Accept json
// @Param token header string true "im token"
// @Param req body api.SendMsg2TagReq true "请求"
// @Produce json
// @Success 0 {object} api.SendMsg2TagResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/send_msg_to_tag [post]
func SendMsg2Tag(c *gin.Context) {
var (
req api.SendMsg2TagReq
resp api.SendMsg2TagResp
reqPb pbOffice.SendMsg2TagReq
respPb *pbOffice.SendMsg2TagResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.SendID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.SendMsg2Tag(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateTag rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
c.JSON(http.StatusOK, resp)
}
// @Summary 获取发送历史记录
// @Description 分页获取发送历史记录
// @Tags 标签
// @ID GetTagSendLogs
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetTagSendLogsReq true "请求"
// @Produce json
// @Success 0 {object} api.GetTagSendLogsResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_send_tag_log [post]
func GetTagSendLogs(c *gin.Context) {
var (
req api.GetTagSendLogsReq
resp api.GetTagSendLogsResp
reqPb pbOffice.GetTagSendLogsReq
respPb *pbOffice.GetTagSendLogsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber,
}
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
maxSizeOption := grpc.MaxCallRecvMsgSize(1024 * 1024 * 20)
respPb, err := client.GetTagSendLogs(context.Background(), &reqPb, maxSizeOption)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTagSendLogs failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetTagSendLogs rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
if respPb.TagSendLogs != nil {
resp.Data.Logs = respPb.TagSendLogs
} else {
resp.Data.Logs = []*pbOffice.TagSendLog{}
}
resp.Data.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage
c.JSON(http.StatusOK, resp)
}
// @Summary 获取该用户的标签信息
// @Description 通过标签id获取该用户的标签信息
// @Tags 标签
// @ID GetUserTagByID
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetUserTagByIDReq true "请求"
// @Produce json
// @Success 0 {object} api.GetUserTagByIDResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_user_tag_by_id [post]
func GetUserTagByID(c *gin.Context) {
var (
req api.GetUserTagByIDReq
resp api.GetUserTagByIDResp
reqPb pbOffice.GetUserTagByIDReq
respPb *pbOffice.GetUserTagByIDResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.UserID = userID
reqPb.OperationID = req.OperationID
reqPb.TagID = req.TagID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserTagByID(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTagByID failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateTag rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp.CommResp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
resp.Data.Tag = respPb.Tag
c.JSON(http.StatusOK, resp)
}

View File

@ -1,670 +0,0 @@
package office
import (
api "Open_IM/pkg/api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tokenverify"
pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/gin-gonic/gin"
"net/http"
"strings"
)
// @Summary 创建一条工作圈
// @Description 用户创建一条工作圈
// @Tags 工作圈
// @ID CreateOneWorkMoment
// @Accept json
// @Param token header string true "im token"
// @Param req body api.CreateOneWorkMomentReq true "请求 atUserList likeUserList permissionGroupList permissionUserList 字段中userName可以不填"
// @Produce json
// @Success 0 {object} api.CreateOneWorkMomentResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/create_one_work_moment [post]
func CreateOneWorkMoment(c *gin.Context) {
var (
req api.CreateOneWorkMomentReq
resp api.CreateOneWorkMomentResp
reqPb pbOffice.CreateOneWorkMomentReq
respPb *pbOffice.CreateOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.WorkMoment.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.CreateOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CreateOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CreateOneWorkMoment rpc server failed" + err.Error()})
return
}
resp.CommResp = api.CommResp{
ErrCode: respPb.CommonResp.ErrCode,
ErrMsg: respPb.CommonResp.ErrMsg,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 删除一条工作圈
// @Description 根据用户工作圈ID删除一条工作圈
// @Tags 工作圈
// @ID DeleteOneWorkMoment
// @Accept json
// @Param token header string true "im token"
// @Param req body api.DeleteOneWorkMomentReq true "请求"
// @Produce json
// @Success 0 {object} api.DeleteOneWorkMomentResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/delete_one_work_moment [post]
func DeleteOneWorkMoment(c *gin.Context) {
var (
req api.DeleteOneWorkMomentReq
resp api.DeleteOneWorkMomentResp
reqPb pbOffice.DeleteOneWorkMomentReq
respPb *pbOffice.DeleteOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.DeleteOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "DeleteOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 点赞一条工作圈
// @Description 工作圈ID点赞一条工作圈
// @Tags 工作圈
// @ID LikeOneWorkMoment
// @Accept json
// @Param token header string true "im token"
// @Param req body api.LikeOneWorkMomentReq true "请求"
// @Produce json
// @Success 0 {object} api.LikeOneWorkMomentResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/like_one_work_moment [post]
func LikeOneWorkMoment(c *gin.Context) {
var (
req api.LikeOneWorkMomentReq
resp api.LikeOneWorkMomentResp
reqPb pbOffice.LikeOneWorkMomentReq
respPb *pbOffice.LikeOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.LikeOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "LikeOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 评论一条工作圈
// @Description 评论一条工作圈
// @Tags 工作圈
// @ID CommentOneWorkMoment
// @Accept json
// @Param token header string true "im token"
// @Param req body api.CommentOneWorkMomentReq true "请求"
// @Produce json
// @Success 0 {object} api.CommentOneWorkMomentResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/comment_one_work_moment [post]
func CommentOneWorkMoment(c *gin.Context) {
var (
req api.CommentOneWorkMomentReq
resp api.CommentOneWorkMomentResp
reqPb pbOffice.CommentOneWorkMomentReq
respPb *pbOffice.CommentOneWorkMomentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.CommentOneWorkMoment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CommentOneWorkMoment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "CommentOneWorkMoment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 删除一条评论
// @Description 删除一条评论
// @Tags 工作圈
// @ID DeleteComment
// @Accept json
// @Param token header string true "im token"
// @Param req body api.DeleteCommentReq true "请求"
// @Produce json
// @Success 0 {object} api.DeleteCommentResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/delete_comment [post]
func DeleteComment(c *gin.Context) {
var (
req api.DeleteCommentReq
resp api.DeleteCommentResp
reqPb pbOffice.DeleteCommentReq
respPb *pbOffice.DeleteCommentResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
var ok bool
var errInfo string
ok, reqPb.OpUserID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.DeleteComment(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteComment rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "DeleteComment rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 通过ID获取工作圈
// @Description 通过ID获取工作圈
// @Tags 工作圈
// @ID GetWorkMomentByID
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetWorkMomentByIDReq true "请求"
// @Produce json
// @Success 0 {object} api.GetWorkMomentByIDResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_work_moment_by_id [post]
func GetWorkMomentByID(c *gin.Context) {
var (
req api.GetWorkMomentByIDReq
resp api.GetWorkMomentByIDResp
reqPb pbOffice.GetWorkMomentByIDReq
respPb *pbOffice.GetWorkMomentByIDResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.OpUserID = userID
reqPb.WorkMomentID = req.WorkMomentID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetWorkMomentByID(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
resp.Data.WorkMoment = &api.WorkMoment{LikeUserList: []*api.WorkMomentUser{}, Comments: []*api.Comment{},
AtUserList: []*api.WorkMomentUser{}, PermissionUserList: []*api.WorkMomentUser{}}
if err := utils.CopyStructFields(&resp.Data.WorkMoment, respPb.WorkMoment); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 查询用户工作圈
// @Description 查询用户工作圈
// @Tags 工作圈
// @ID GetUserWorkMoments
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetUserWorkMomentsReq true "请求"
// @Produce json
// @Success 0 {object} api.GetUserWorkMomentsResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_user_work_moments [post]
func GetUserWorkMoments(c *gin.Context) {
var (
req api.GetUserWorkMomentsReq
resp api.GetUserWorkMomentsResp
reqPb pbOffice.GetUserWorkMomentsReq
respPb *pbOffice.GetUserWorkMomentsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var opUserID string
ok, opUserID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber,
}
reqPb.OpUserID = opUserID
reqPb.UserID = req.UserID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserWorkMoments(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserWorkMoments rpc server failed" + err.Error()})
return
}
resp.Data.WorkMoments = []*api.WorkMoment{}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
for _, v := range respPb.WorkMoments {
workMoment := api.WorkMoment{
WorkMomentID: v.WorkMomentID,
UserID: v.UserID,
Content: v.Content,
FaceURL: v.FaceURL,
UserName: v.UserName,
CreateTime: v.CreateTime,
Comments: make([]*api.Comment, len(v.Comments)),
LikeUserList: make([]*api.WorkMomentUser, len(v.LikeUserList)),
AtUserList: make([]*api.WorkMomentUser, len(v.AtUserList)),
PermissionUserList: make([]*api.WorkMomentUser, len(v.PermissionUserList)),
Permission: v.Permission,
}
for i, comment := range v.Comments {
workMoment.Comments[i] = &api.Comment{
UserID: comment.UserID,
UserName: comment.UserName,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
}
for i, likeUser := range v.LikeUserList {
workMoment.LikeUserList[i] = &api.WorkMomentUser{
UserID: likeUser.UserID,
UserName: likeUser.UserName,
}
}
for i, atUser := range v.AtUserList {
workMoment.AtUserList[i] = &api.WorkMomentUser{
UserID: atUser.UserID,
UserName: atUser.UserName,
}
}
for i, permissionUser := range v.PermissionUserList {
workMoment.PermissionUserList[i] = &api.WorkMomentUser{
UserID: permissionUser.UserID,
UserName: permissionUser.UserName,
}
}
resp.Data.WorkMoments = append(resp.Data.WorkMoments, &workMoment)
}
resp.Data.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
// @Summary 查询自己大工作圈页面
// @Description 查询用户工作圈页面
// @Tags 工作圈
// @ID GetUserFriendWorkMoments
// @Accept json
// @Param token header string true "im token"
// @Param req body api.GetUserFriendWorkMomentsReq true "请求"
// @Produce json
// @Success 0 {object} api.GetUserFriendWorkMomentsResp
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /office/get_user_friend_work_moments [post]
func GetUserFriendWorkMoments(c *gin.Context) {
var (
req api.GetUserFriendWorkMomentsReq
resp api.GetUserFriendWorkMomentsResp
reqPb pbOffice.GetUserFriendWorkMomentsReq
respPb *pbOffice.GetUserFriendWorkMomentsResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: req.PageNumber,
ShowNumber: req.ShowNumber,
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.GetUserFriendWorkMoments(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "GetUserFriendWorkMoments rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
//if err := utils.CopyStructFields(&resp.Map.WorkMoments, respPb.WorkMoments); err != nil {
// log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
//}
resp.Data.WorkMoments = []*api.WorkMoment{}
for _, v := range respPb.WorkMoments {
workMoment := api.WorkMoment{
WorkMomentID: v.WorkMomentID,
UserID: v.UserID,
Content: v.Content,
FaceURL: v.FaceURL,
UserName: v.UserName,
CreateTime: v.CreateTime,
Comments: make([]*api.Comment, len(v.Comments)),
LikeUserList: make([]*api.WorkMomentUser, len(v.LikeUserList)),
AtUserList: make([]*api.WorkMomentUser, len(v.AtUserList)),
PermissionUserList: make([]*api.WorkMomentUser, len(v.PermissionUserList)),
Permission: v.Permission,
}
for i, comment := range v.Comments {
workMoment.Comments[i] = &api.Comment{
UserID: comment.UserID,
UserName: comment.UserName,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
}
for i, likeUser := range v.LikeUserList {
workMoment.LikeUserList[i] = &api.WorkMomentUser{
UserID: likeUser.UserID,
UserName: likeUser.UserName,
}
}
for i, atUser := range v.AtUserList {
workMoment.AtUserList[i] = &api.WorkMomentUser{
UserID: atUser.UserID,
UserName: atUser.UserName,
}
}
for i, permissionUser := range v.PermissionUserList {
workMoment.PermissionUserList[i] = &api.WorkMomentUser{
UserID: permissionUser.UserID,
UserName: permissionUser.UserName,
}
}
resp.Data.WorkMoments = append(resp.Data.WorkMoments, &workMoment)
}
resp.Data.ShowNumber = respPb.Pagination.ShowNumber
resp.Data.CurrentPage = respPb.Pagination.CurrentPage
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}
func SetUserWorkMomentsLevel(c *gin.Context) {
var (
req api.SetUserWorkMomentsLevelReq
resp api.SetUserWorkMomentsLevelResp
reqPb pbOffice.SetUserWorkMomentsLevelReq
respPb *pbOffice.SetUserWorkMomentsLevelResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "bind json failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": "bind json failed " + err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
var ok bool
var errInfo string
var userID string
ok, userID, errInfo = tokenverify.GetUserIDFromToken(c.Request.Header.Get("token"), req.OperationID)
if !ok {
errMsg := req.OperationID + " " + "GetUserIDFromToken failed " + errInfo + " token:" + c.Request.Header.Get("token")
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
if err := utils.CopyStructFields(&reqPb, req); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
reqPb.UserID = userID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImOfficeName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbOffice.NewOfficeServiceClient(etcdConn)
respPb, err := client.SetUserWorkMomentsLevel(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetUserWorkMomentsLevel rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "SetUserWorkMomentsLevel rpc server failed" + err.Error()})
return
}
if err := utils.CopyStructFields(&resp, respPb.CommonResp); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, resp)
}

View File

@ -9,7 +9,7 @@ import (
"Open_IM/pkg/common/tokenverify"
cacheRpc "Open_IM/pkg/proto/cache"
pbRelay "Open_IM/pkg/proto/relay"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
rpc "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
@ -52,10 +52,10 @@ func GetUsersInfoFromCache(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call rpc server failed"})
return
}
var publicUserInfoList []*open_im_sdk.PublicUserInfo
var publicUserInfoList []*sdkws.PublicUserInfo
for _, v := range RpcResp.UserInfoList {
publicUserInfoList = append(publicUserInfoList,
&open_im_sdk.PublicUserInfo{UserID: v.UserID, Nickname: v.Nickname, FaceURL: v.FaceURL, Gender: v.Gender, Ex: v.Ex})
&sdkws.PublicUserInfo{UserID: v.UserID, Nickname: v.Nickname, FaceURL: v.FaceURL, Gender: v.Gender, Ex: v.Ex})
}
resp := api.GetUsersInfoResp{CommResp: api.CommResp{ErrCode: RpcResp.CommonResp.ErrCode, ErrMsg: RpcResp.CommonResp.ErrMsg}, UserInfoList: publicUserInfoList}
resp.Data = jsonData.JsonDataList(resp.UserInfoList)
@ -155,7 +155,7 @@ func GetBlackIDListFromCache(c *gin.Context) {
// @Param token header string true "im token"
// @Param req body api.GetUsersInfoReq true "请求体"
// @Produce json
// @Success 0 {object} api.GetUsersInfoResp{Map=[]open_im_sdk.PublicUserInfo}
// @Success 0 {object} api.GetUsersInfoResp{Map=[]sdkws.PublicUserInfo}
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /user/get_users_info [post]
@ -195,10 +195,10 @@ func GetUsersPublicInfo(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": "call rpc server failed"})
return
}
var publicUserInfoList []*open_im_sdk.PublicUserInfo
var publicUserInfoList []*sdkws.PublicUserInfo
for _, v := range RpcResp.UserInfoList {
publicUserInfoList = append(publicUserInfoList,
&open_im_sdk.PublicUserInfo{UserID: v.UserID, Nickname: v.Nickname, FaceURL: v.FaceURL, Gender: v.Gender, Ex: v.Ex})
&sdkws.PublicUserInfo{UserID: v.UserID, Nickname: v.Nickname, FaceURL: v.FaceURL, Gender: v.Gender, Ex: v.Ex})
}
resp := api.GetUsersInfoResp{CommResp: api.CommResp{ErrCode: RpcResp.CommonResp.ErrCode, ErrMsg: RpcResp.CommonResp.ErrMsg}, UserInfoList: publicUserInfoList}
@ -226,7 +226,7 @@ func UpdateUserInfo(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
req := &rpc.UpdateUserInfoReq{UserInfo: &open_im_sdk.UserInfo{}}
req := &rpc.UpdateUserInfoReq{UserInfo: &sdkws.UserInfo{}}
utils.CopyStructFields(req.UserInfo, &params)
req.OperationID = params.OperationID
var ok bool
@ -317,7 +317,7 @@ func SetGlobalRecvMessageOpt(c *gin.Context) {
// @Param token header string true "im token"
// @Param req body api.GetSelfUserInfoReq true "请求体"
// @Produce json
// @Success 0 {object} api.GetSelfUserInfoResp{data=open_im_sdk.UserInfo}
// @Success 0 {object} api.GetSelfUserInfoResp{data=sdkws.UserInfo}
// @Failure 500 {object} api.Swagger500Resp "errCode为500 一般为服务器内部错误"
// @Failure 400 {object} api.Swagger400Resp "errCode为400 一般为参数输入错误, token未带上等"
// @Router /user/get_self_user_info [post]
@ -482,7 +482,7 @@ func GetUsers(c *gin.Context) {
reqPb.UserID = req.UserID
reqPb.UserName = req.UserName
reqPb.Content = req.Content
reqPb.Pagination = &open_im_sdk.RequestPagination{ShowNumber: req.ShowNumber, PageNumber: req.PageNumber}
reqPb.Pagination = &sdkws.RequestPagination{ShowNumber: req.ShowNumber, PageNumber: req.PageNumber}
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"

View File

@ -1,128 +0,0 @@
package admin
import (
apiStruct "Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
pbAdmin "Open_IM/pkg/proto/admin_cms"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
url2 "net/url"
"github.com/gin-gonic/gin"
)
var (
minioClient *minio.Client
)
func init() {
log.NewPrivateLog(constant.LogFileName)
operationID := utils.OperationIDGenerator()
log.NewInfo(operationID, utils.GetSelfFuncName(), "minio config: ", config.Config.Credential.Minio)
var initUrl string
if config.Config.Credential.Minio.EndpointInnerEnable {
initUrl = config.Config.Credential.Minio.EndpointInner
} else {
initUrl = config.Config.Credential.Minio.Endpoint
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "use initUrl: ", initUrl)
minioUrl, err := url2.Parse(initUrl)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "parse failed, please check config/config.yaml", err.Error())
return
}
opts := &minio.Options{
Creds: credentials.NewStaticV4(config.Config.Credential.Minio.AccessKeyID, config.Config.Credential.Minio.SecretAccessKey, ""),
}
if minioUrl.Scheme == "http" {
opts.Secure = false
} else if minioUrl.Scheme == "https" {
opts.Secure = true
}
log.NewInfo(operationID, utils.GetSelfFuncName(), "Parse ok ", config.Config.Credential.Minio)
minioClient, err = minio.New(minioUrl.Host, opts)
log.NewInfo(operationID, utils.GetSelfFuncName(), "new ok ", config.Config.Credential.Minio)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "init minio client failed", err.Error())
return
}
}
func GetUserToken(c *gin.Context) {
var (
req apiStruct.GetUserTokenRequest
resp apiStruct.GetUserTokenResponse
reqPb pbAdmin.GetUserTokenReq
respPb *pbAdmin.GetUserTokenResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = req.OperationID
reqPb.UserID = req.UserID
reqPb.PlatformID = req.PlatFormID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbAdmin.NewAdminCMSClient(etcdConn)
respPb, err := client.GetUserToken(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp.Token = respPb.Token
resp.ExpTime = respPb.ExpTime
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
// register
func AdminLogin(c *gin.Context) {
var (
req apiStruct.AdminLoginRequest
resp apiStruct.AdminLoginResponse
reqPb pbAdmin.AdminLoginReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.Secret = req.Secret
reqPb.AdminID = req.AdminName
reqPb.OperationID = utils.OperationIDGenerator()
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbAdmin.NewAdminCMSClient(etcdConn)
respPb, err := client.AdminLogin(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp.FaceURL = respPb.FaceURL
resp.UserName = respPb.UserName
resp.Token = respPb.Token
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -1,63 +0,0 @@
package friend
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
pbAdmin "Open_IM/pkg/proto/admin_cms"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func GetUserFriends(c *gin.Context) {
var (
req cms_struct.GetFriendsReq
resp cms_struct.GetFriendsResp
reqPb pbAdmin.GetUserFriendsReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Pagination = &pbCommon.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.OperationID = req.OperationID
reqPb.UserID = req.UserID
reqPb.FriendUserName = req.FriendUserName
reqPb.FriendUserID = req.FriendUserID
client := pbAdmin.NewAdminCMSClient(etcdConn)
respPb, err := client.GetUserFriends(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetUserInfo failed ", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
for _, v := range respPb.FriendInfoList {
friend := &cms_struct.FriendInfo{}
utils.CopyStructFields(friend, v)
friend.Nickname = v.FriendUser.Nickname
friend.UserID = v.FriendUser.UserID
resp.FriendInfoList = append(resp.FriendInfoList, friend)
}
resp.FriendNums = respPb.FriendNums
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -1,109 +0,0 @@
package group
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
common "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
pbGroup "Open_IM/pkg/proto/group"
"github.com/gin-gonic/gin"
)
func GetGroups(c *gin.Context) {
var (
req cms_struct.GetGroupsRequest
resp cms_struct.GetGroupsResponse
reqPb pbGroup.GetGroupsReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Pagination = &common.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
reqPb.GroupID = req.GroupID
reqPb.GroupName = req.GroupName
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroups(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetUserInfo failed ", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
for _, v := range respPb.CMSGroups {
groupResp := cms_struct.GroupResponse{}
utils.CopyStructFields(&groupResp, v.GroupInfo)
groupResp.GroupOwnerName = v.GroupOwnerUserName
groupResp.GroupOwnerID = v.GroupOwnerUserID
resp.Groups = append(resp.Groups, groupResp)
}
resp.GroupNums = int(respPb.GroupNum)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
func GetGroupMembers(c *gin.Context) {
var (
req cms_struct.GetGroupMembersRequest
reqPb pbGroup.GetGroupMembersCMSReq
resp cms_struct.GetGroupMembersResponse
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.Pagination = &common.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
}
reqPb.GroupID = req.GroupID
reqPb.UserName = req.UserName
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroupMembersCMS(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetGroupMembersCMS failed:", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp.ResponsePagination = cms_struct.ResponsePagination{
CurrentPage: int(respPb.Pagination.CurrentPage),
ShowNumber: int(respPb.Pagination.ShowNumber),
}
resp.MemberNums = int(respPb.MemberNums)
for _, groupMember := range respPb.Members {
memberResp := cms_struct.GroupMemberResponse{}
utils.CopyStructFields(&memberResp, groupMember)
resp.GroupMembers = append(resp.GroupMembers, memberResp)
}
log.NewInfo("", utils.GetSelfFuncName(), "req: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -1,59 +0,0 @@
package messageCMS
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
pbAdminCMS "Open_IM/pkg/proto/admin_cms"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func GetChatLogs(c *gin.Context) {
var (
req cms_struct.GetChatLogsReq
resp cms_struct.GetChatLogsResp
reqPb pbAdminCMS.GetChatLogsReq
)
if err := c.Bind(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
}
utils.CopyStructFields(&reqPb, &req)
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbAdminCMS.NewAdminCMSClient(etcdConn)
respPb, err := client.GetChatLogs(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetChatLogs rpc failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
for _, v := range respPb.ChatLogs {
chatLog := cms_struct.ChatLog{}
utils.CopyStructFields(&chatLog, v)
resp.ChatLogs = append(resp.ChatLogs, &chatLog)
}
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.ChatLogsNum = int(respPb.ChatLogsNum)
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -1,62 +0,0 @@
package cmsapi
import (
"Open_IM/internal/cms_api/admin"
"Open_IM/internal/cms_api/friend"
"Open_IM/internal/cms_api/group"
messageCMS "Open_IM/internal/cms_api/message_cms"
"Open_IM/internal/cms_api/middleware"
"Open_IM/internal/cms_api/statistics"
"Open_IM/internal/cms_api/user"
"Open_IM/pkg/common/config"
promePkg "Open_IM/pkg/common/prometheus"
"github.com/gin-gonic/gin"
)
func NewGinRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
baseRouter := gin.New()
baseRouter.Use(gin.Recovery())
baseRouter.Use(middleware.CorsHandler())
if config.Config.Prometheus.Enable {
baseRouter.GET("/metrics", promePkg.PrometheusHandler())
}
router := baseRouter.Group("/cms")
adminRouterGroup := router.Group("/admin")
{
adminRouterGroup.POST("/login", admin.AdminLogin)
adminRouterGroup.Use(middleware.JWTAuth())
adminRouterGroup.POST("/get_user_token", admin.GetUserToken)
}
r2 := router.Group("")
r2.Use(middleware.JWTAuth())
statisticsRouterGroup := r2.Group("/statistics")
{
statisticsRouterGroup.POST("/get_messages_statistics", statistics.GetMessagesStatistics)
statisticsRouterGroup.POST("/get_user_statistics", statistics.GetUserStatistics)
statisticsRouterGroup.POST("/get_group_statistics", statistics.GetGroupStatistics)
statisticsRouterGroup.POST("/get_active_user", statistics.GetActiveUser)
statisticsRouterGroup.POST("/get_active_group", statistics.GetActiveGroup)
}
groupRouterGroup := r2.Group("/group")
{
groupRouterGroup.POST("/get_groups", group.GetGroups)
groupRouterGroup.POST("/get_group_members", group.GetGroupMembers)
}
userRouterGroup := r2.Group("/user")
{
userRouterGroup.POST("/get_user_id_by_email_phone", user.GetUserIDByEmailAndPhoneNumber)
}
messageCMSRouterGroup := r2.Group("/message")
{
messageCMSRouterGroup.POST("/get_chat_logs", messageCMS.GetChatLogs)
}
friendCMSRouterGroup := r2.Group("/friend")
{
friendCMSRouterGroup.POST("/get_friends", friend.GetUserFriends)
}
return baseRouter
}

View File

@ -1,278 +0,0 @@
package statistics
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
admin "Open_IM/pkg/proto/admin_cms"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func GetMessagesStatistics(c *gin.Context) {
var (
req cms_struct.GetMessageStatisticsRequest
resp cms_struct.GetMessageStatisticsResponse
reqPb admin.GetMessageStatisticsReq
)
reqPb.StatisticsReq = &admin.StatisticsReq{}
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := admin.NewAdminCMSClient(etcdConn)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*100)
defer cancel()
respPb, err := client.GetMessageStatistics(ctx, &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetMessageStatistics failed", err.Error())
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
resp.GroupMessageNum = int(respPb.GroupMessageNum)
resp.PrivateMessageNum = int(respPb.PrivateMessageNum)
for _, v := range respPb.PrivateMessageNumList {
resp.PrivateMessageNumList = append(resp.PrivateMessageNumList, struct {
Date string "json:\"date\""
MessageNum int "json:\"messageNum\""
}{
Date: v.Date,
MessageNum: int(v.Num),
})
}
for _, v := range respPb.GroupMessageNumList {
resp.GroupMessageNumList = append(resp.GroupMessageNumList, struct {
Date string "json:\"date\""
MessageNum int "json:\"messageNum\""
}{
Date: v.Date,
MessageNum: int(v.Num),
})
}
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
func GetUserStatistics(c *gin.Context) {
var (
req cms_struct.GetUserStatisticsRequest
resp cms_struct.GetUserStatisticsResponse
reqPb admin.GetUserStatisticsReq
)
reqPb.StatisticsReq = &admin.StatisticsReq{}
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := admin.NewAdminCMSClient(etcdConn)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*100)
defer cancel()
respPb, err := client.GetUserStatistics(ctx, &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetUserStatistics failed", err.Error(), reqPb.String())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp.ActiveUserNum = int(respPb.ActiveUserNum)
resp.IncreaseUserNum = int(respPb.IncreaseUserNum)
resp.TotalUserNum = int(respPb.TotalUserNum)
for _, v := range respPb.ActiveUserNumList {
resp.ActiveUserNumList = append(resp.ActiveUserNumList, struct {
Date string "json:\"date\""
ActiveUserNum int "json:\"activeUserNum\""
}{
Date: v.Date,
ActiveUserNum: int(v.Num),
})
}
for _, v := range respPb.IncreaseUserNumList {
resp.IncreaseUserNumList = append(resp.IncreaseUserNumList, struct {
Date string "json:\"date\""
IncreaseUserNum int "json:\"increaseUserNum\""
}{
Date: v.Date,
IncreaseUserNum: int(v.Num),
})
}
for _, v := range respPb.TotalUserNumList {
resp.TotalUserNumList = append(resp.TotalUserNumList, struct {
Date string "json:\"date\""
TotalUserNum int "json:\"totalUserNum\""
}{
Date: v.Date,
TotalUserNum: int(v.Num),
})
}
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
func GetGroupStatistics(c *gin.Context) {
var (
req cms_struct.GetGroupStatisticsRequest
resp cms_struct.GetGroupStatisticsResponse
reqPb admin.GetGroupStatisticsReq
)
reqPb.StatisticsReq = &admin.StatisticsReq{}
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := admin.NewAdminCMSClient(etcdConn)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*100)
defer cancel()
respPb, err := client.GetGroupStatistics(ctx, &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetGroupStatistics failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
// utils.CopyStructFields(&resp, respPb)
resp.IncreaseGroupNum = int(respPb.GetIncreaseGroupNum())
resp.TotalGroupNum = int(respPb.GetTotalGroupNum())
for _, v := range respPb.IncreaseGroupNumList {
resp.IncreaseGroupNumList = append(resp.IncreaseGroupNumList,
struct {
Date string "json:\"date\""
IncreaseGroupNum int "json:\"increaseGroupNum\""
}{
Date: v.Date,
IncreaseGroupNum: int(v.Num),
})
}
for _, v := range respPb.TotalGroupNumList {
resp.TotalGroupNumList = append(resp.TotalGroupNumList,
struct {
Date string "json:\"date\""
TotalGroupNum int "json:\"totalGroupNum\""
}{
Date: v.Date,
TotalGroupNum: int(v.Num),
})
}
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
func GetActiveUser(c *gin.Context) {
var (
req cms_struct.GetActiveUserRequest
resp cms_struct.GetActiveUserResponse
reqPb admin.GetActiveUserReq
)
reqPb.StatisticsReq = &admin.StatisticsReq{}
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := admin.NewAdminCMSClient(etcdConn)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*100)
defer cancel()
respPb, err := client.GetActiveUser(ctx, &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetActiveUser failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
utils.CopyStructFields(&resp.ActiveUserList, respPb.Users)
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}
func GetActiveGroup(c *gin.Context) {
var (
req cms_struct.GetActiveGroupRequest
resp cms_struct.GetActiveGroupResponse
reqPb admin.GetActiveGroupReq
)
reqPb.StatisticsReq = &admin.StatisticsReq{}
if err := c.BindJSON(&req); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
reqPb.OperationID = utils.OperationIDGenerator()
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", req)
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := admin.NewAdminCMSClient(etcdConn)
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*100)
defer cancel()
respPb, err := client.GetActiveGroup(ctx, &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetActiveGroup failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
for _, group := range respPb.Groups {
resp.ActiveGroupList = append(resp.ActiveGroupList, struct {
GroupName string "json:\"groupName\""
GroupId string "json:\"groupID\""
MessageNum int "json:\"messageNum\""
}{
GroupName: group.GroupName,
GroupId: group.GroupId,
MessageNum: int(group.MessageNum),
})
}
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "resp: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -1,53 +0,0 @@
package user
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/cms_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
pbAdminCms "Open_IM/pkg/proto/admin_cms"
common "Open_IM/pkg/proto/sdkws"
pb "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func GetUserIDByEmailAndPhoneNumber(c *gin.Context) {
var (
req cmsstruct.GetUserIDByEmailAndPhoneNumberRequest
resp cmsstruct.GetUserIDByEmailAndPhoneNumberResponse
reqPb pbAdminCms.GetUserIDByEmailAndPhoneNumberReq
respPb *pbAdminCms.GetUserIDByEmailAndPhoneNumberResp
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 400, "errMsg": err.Error()})
return
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req)
reqPb.OperationID = req.OperationID
reqPb.Email = req.Email
reqPb.PhoneNumber = req.PhoneNumber
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName, reqPb.OperationID)
if etcdConn == nil {
errMsg := reqPb.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(reqPb.OperationID, errMsg)
c.JSON(http.StatusInternalServerError, gin.H{"errCode": 500, "errMsg": errMsg})
return
}
client := pbAdminCms.NewAdminCMSClient(etcdConn)
respPb, err := client.GetUserIDByEmailAndPhoneNumber(context.Background(), &reqPb)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "rpc failed", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": 500, "errMsg": err.Error()})
return
}
resp.UserIDList = respPb.UserIDList
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "req: ", resp)
c.JSON(http.StatusOK, gin.H{"errCode": respPb.CommonResp.ErrCode, "errMsg": respPb.CommonResp.ErrMsg, "data": resp})
}

View File

@ -6,6 +6,32 @@ import (
"errors"
)
func GetUsersInfo(ctx context.Context, args ...interface{}) ([]*sdkws.UserInfo, error) {
return nil, errors.New("TODO:GetUserInfo")
//func GetUsersInfo(ctx context.Context, args ...interface{}) ([]*sdkws.UserInfo, error) {
// return nil, errors.New("TODO:GetUserInfo")
//}
func NewUserCheck() *UserCheck {
return &UserCheck{}
}
type UserCheck struct{}
func (u *UserCheck) GetUsersInfos(ctx context.Context, userIDs []string, complete bool) ([]*sdkws.UserInfo, error) {
return nil, errors.New("todo")
}
func (u *UserCheck) GetUsersInfoMap(ctx context.Context, userIDs []string, complete bool) (map[string]*sdkws.UserInfo, error) {
return nil, errors.New("todo")
}
func (u *UserCheck) GetPublicUserInfo(ctx context.Context, userID string) (*sdkws.PublicUserInfo, error) {
return nil, errors.New("todo")
}
func (u *UserCheck) GetPublicUserInfos(ctx context.Context, userIDs []string, complete bool) ([]*sdkws.PublicUserInfo, error) {
return nil, errors.New("todo")
}
func (u *UserCheck) GetPublicUserInfoMap(ctx context.Context, userIDs []string, complete bool) (map[string]*sdkws.PublicUserInfo, error) {
return nil, errors.New("todo")
}

View File

@ -1,18 +1,17 @@
package notification
package msg
import (
"Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func SetConversationNotification(operationID, sendID, recvID string, contentType int, m proto.Message, tips open_im_sdk.TipsComm) {
func SetConversationNotification(operationID, sendID, recvID string, contentType int, m proto.Message, tips sdkws.TipsComm) {
log.NewInfo(operationID, "args: ", sendID, recvID, contentType, m.String(), tips.String())
var err error
tips.Detail, err = proto.Marshal(m)
@ -26,7 +25,7 @@ func SetConversationNotification(operationID, sendID, recvID string, contentType
EmitDefaults: false,
}
tips.JsonDetail, _ = marshaler.MarshalToString(m)
var n msg.NotificationMsg
var n NotificationMsg
n.SendID = sendID
n.RecvID = recvID
n.ContentType = int32(contentType)
@ -38,18 +37,18 @@ func SetConversationNotification(operationID, sendID, recvID string, contentType
log.Error(operationID, utils.GetSelfFuncName(), "Marshal failed ", err.Error(), tips.String())
return
}
msg.Notification(&n)
Notification(&n)
}
// SetPrivate调用
func ConversationSetPrivateNotification(operationID, sendID, recvID string, isPrivateChat bool) {
func ConversationSetPrivateNotification(ctx context.Context, sendID, recvID string, isPrivateChat bool) {
log.NewInfo(operationID, utils.GetSelfFuncName())
conversationSetPrivateTips := &open_im_sdk.ConversationSetPrivateTips{
conversationSetPrivateTips := &sdkws.ConversationSetPrivateTips{
RecvID: recvID,
SendID: sendID,
IsPrivate: isPrivateChat,
}
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
var tipsMsg string
if isPrivateChat == true {
tipsMsg = config.Config.Notification.ConversationSetPrivate.DefaultTips.OpenTips
@ -63,23 +62,23 @@ func ConversationSetPrivateNotification(operationID, sendID, recvID string, isPr
// 会话改变
func ConversationChangeNotification(ctx context.Context, userID string) {
log.NewInfo(operationID, utils.GetSelfFuncName())
ConversationChangedTips := &open_im_sdk.ConversationUpdateTips{
ConversationChangedTips := &sdkws.ConversationUpdateTips{
UserID: userID,
}
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.DefaultTips = config.Config.Notification.ConversationOptUpdate.DefaultTips.Tips
SetConversationNotification(operationID, userID, userID, constant.ConversationOptChangeNotification, ConversationChangedTips, tips)
}
// 会话未读数同步
func ConversationUnreadChangeNotification(operationID, userID, conversationID string, updateUnreadCountTime int64) {
//会话未读数同步
func ConversationUnreadChangeNotification(context context.Context, userID, conversationID string, updateUnreadCountTime int64) {
log.NewInfo(operationID, utils.GetSelfFuncName())
ConversationChangedTips := &open_im_sdk.ConversationUpdateTips{
ConversationChangedTips := &sdkws.ConversationUpdateTips{
UserID: userID,
ConversationIDList: []string{conversationID},
UpdateUnreadCountTime: updateUnreadCountTime,
}
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.DefaultTips = config.Config.Notification.ConversationOptUpdate.DefaultTips.Tips
SetConversationNotification(operationID, userID, userID, constant.ConversationUnreadNotification, ConversationChangedTips, tips)
}

View File

@ -5,7 +5,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
"Open_IM/pkg/proto/msg"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
)
@ -16,7 +16,7 @@ func ExtendMessageUpdatedNotification(operationID, sendID string, sourceID strin
m.SourceID = req.SourceID
m.OpUserID = req.OpUserID
m.SessionType = req.SessionType
keyMap := make(map[string]*open_im_sdk.KeyValue)
keyMap := make(map[string]*sdkws.KeyValue)
for _, valueResp := range resp.Result {
if valueResp.ErrCode == 0 {
keyMap[valueResp.KeyValue.TypeKey] = valueResp.KeyValue
@ -39,7 +39,7 @@ func ExtendMessageDeleteNotification(operationID, sendID string, sourceID string
m.SourceID = req.SourceID
m.OpUserID = req.OpUserID
m.SessionType = req.SessionType
keyMap := make(map[string]*open_im_sdk.KeyValue)
keyMap := make(map[string]*sdkws.KeyValue)
for _, valueResp := range resp.Result {
if valueResp.ErrCode == 0 {
keyMap[valueResp.KeyValue.TypeKey] = valueResp.KeyValue
@ -68,7 +68,7 @@ func messageReactionSender(operationID, sendID string, sourceID string, sessionT
}
pbData := msg.SendMsgReq{
OperationID: operationID,
MsgData: &open_im_sdk.MsgData{
MsgData: &sdkws.MsgData{
SendID: sendID,
ClientMsgID: utils.GetMsgID(sendID),
SessionType: sessionType,

View File

@ -8,7 +8,7 @@ import (
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tracelog"
pbFriend "Open_IM/pkg/proto/friend"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/golang/protobuf/jsonpb"
@ -30,7 +30,7 @@ func getFromToUserNickname(fromUserID, toUserID string) (string, string, error)
func friendNotification(operationID, fromUserID, toUserID string, contentType int32, m proto.Message) {
log.Info(operationID, utils.GetSelfFuncName(), "args: ", contentType)
var err error
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.Detail, err = proto.Marshal(m)
if err != nil {
log.Error(operationID, "Marshal failed ", err.Error(), m.String())
@ -93,14 +93,14 @@ func friendNotification(operationID, fromUserID, toUserID string, contentType in
}
func FriendApplicationAddNotification(ctx context.Context, req *pbFriend.AddFriendReq) {
FriendApplicationTips := open_im_sdk.FriendApplicationTips{FromToUserID: &open_im_sdk.FromToUserID{}}
FriendApplicationTips := sdkws.FriendApplicationTips{FromToUserID: &sdkws.FromToUserID{}}
FriendApplicationTips.FromToUserID.FromUserID = req.FromUserID
FriendApplicationTips.FromToUserID.ToUserID = req.ToUserID
friendNotification(tracelog.GetOperationID(ctx), req.FromUserID, req.ToUserID, constant.FriendApplicationNotification, &FriendApplicationTips)
}
func FriendApplicationAgreedNotification(ctx context.Context, req *pbFriend.RespondFriendApplyReq) {
FriendApplicationApprovedTips := open_im_sdk.FriendApplicationApprovedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
FriendApplicationApprovedTips := sdkws.FriendApplicationApprovedTips{FromToUserID: &sdkws.FromToUserID{}}
FriendApplicationApprovedTips.FromToUserID.FromUserID = req.FromUserID
FriendApplicationApprovedTips.FromToUserID.ToUserID = req.ToUserID
FriendApplicationApprovedTips.HandleMsg = req.HandleMsg
@ -108,7 +108,7 @@ func FriendApplicationAgreedNotification(ctx context.Context, req *pbFriend.Resp
}
func FriendApplicationRefusedNotification(ctx context.Context, req *pbFriend.RespondFriendApplyReq) {
FriendApplicationApprovedTips := open_im_sdk.FriendApplicationApprovedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
FriendApplicationApprovedTips := sdkws.FriendApplicationApprovedTips{FromToUserID: &sdkws.FromToUserID{}}
FriendApplicationApprovedTips.FromToUserID.FromUserID = req.FromUserID
FriendApplicationApprovedTips.FromToUserID.ToUserID = req.ToUserID
FriendApplicationApprovedTips.HandleMsg = req.HandleMsg
@ -116,7 +116,7 @@ func FriendApplicationRefusedNotification(ctx context.Context, req *pbFriend.Res
}
func FriendAddedNotification(ctx context.Context, operationID, opUserID, fromUserID, toUserID string) {
friendAddedTips := open_im_sdk.FriendAddedTips{Friend: &open_im_sdk.FriendInfo{}, OpUser: &open_im_sdk.PublicUserInfo{}}
friendAddedTips := sdkws.FriendAddedTips{Friend: &sdkws.FriendInfo{}, OpUser: &sdkws.PublicUserInfo{}}
user, err := check.GetUsersInfo(context.Background(), opUserID)
if err != nil {
return
@ -135,28 +135,28 @@ func FriendAddedNotification(ctx context.Context, operationID, opUserID, fromUse
}
func FriendDeletedNotification(ctx context.Context, req *pbFriend.DeleteFriendReq) {
friendDeletedTips := open_im_sdk.FriendDeletedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
friendDeletedTips := sdkws.FriendDeletedTips{FromToUserID: &sdkws.FromToUserID{}}
friendDeletedTips.FromToUserID.FromUserID = req.OwnerUserID
friendDeletedTips.FromToUserID.ToUserID = req.FriendUserID
friendNotification(tracelog.GetOperationID(ctx), req.OwnerUserID, req.FriendUserID, constant.FriendDeletedNotification, &friendDeletedTips)
}
func FriendRemarkSetNotification(ctx context.Context, fromUserID, toUserID string) {
friendInfoChangedTips := open_im_sdk.FriendInfoChangedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
friendInfoChangedTips := sdkws.FriendInfoChangedTips{FromToUserID: &sdkws.FromToUserID{}}
friendInfoChangedTips.FromToUserID.FromUserID = fromUserID
friendInfoChangedTips.FromToUserID.ToUserID = toUserID
friendNotification(tracelog.GetOperationID(ctx), fromUserID, toUserID, constant.FriendRemarkSetNotification, &friendInfoChangedTips)
}
func BlackAddedNotification(ctx context.Context, req *pbFriend.AddBlackReq) {
blackAddedTips := open_im_sdk.BlackAddedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
blackAddedTips := sdkws.BlackAddedTips{FromToUserID: &sdkws.FromToUserID{}}
blackAddedTips.FromToUserID.FromUserID = req.OwnerUserID
blackAddedTips.FromToUserID.ToUserID = req.BlackUserID
friendNotification(tracelog.GetOperationID(ctx), req.OwnerUserID, req.BlackUserID, constant.BlackAddedNotification, &blackAddedTips)
}
func BlackDeletedNotification(ctx context.Context, req *pbFriend.RemoveBlackReq) {
blackDeletedTips := open_im_sdk.BlackDeletedTips{FromToUserID: &open_im_sdk.FromToUserID{}}
blackDeletedTips := sdkws.BlackDeletedTips{FromToUserID: &sdkws.FromToUserID{}}
blackDeletedTips.FromToUserID.FromUserID = req.OwnerUserID
blackDeletedTips.FromToUserID.ToUserID = req.BlackUserID
friendNotification(tracelog.GetOperationID(ctx), req.OwnerUserID, req.BlackUserID, constant.BlackDeletedNotification, &blackDeletedTips)
@ -164,11 +164,11 @@ func BlackDeletedNotification(ctx context.Context, req *pbFriend.RemoveBlackReq)
// send to myself
func UserInfoUpdatedNotification(ctx context.Context, opUserID string, changedUserID string) {
selfInfoUpdatedTips := open_im_sdk.UserInfoUpdatedTips{UserID: changedUserID}
selfInfoUpdatedTips := sdkws.UserInfoUpdatedTips{UserID: changedUserID}
friendNotification(tracelog.GetOperationID(ctx), opUserID, changedUserID, constant.UserInfoUpdatedNotification, &selfInfoUpdatedTips)
}
func FriendInfoUpdatedNotification(ctx context.Context, changedUserID string, needNotifiedUserID string, opUserID string) {
selfInfoUpdatedTips := open_im_sdk.UserInfoUpdatedTips{UserID: changedUserID}
selfInfoUpdatedTips := sdkws.UserInfoUpdatedTips{UserID: changedUserID}
friendNotification(tracelog.GetOperationID(ctx), opUserID, needNotifiedUserID, constant.FriendInfoUpdatedNotification, &selfInfoUpdatedTips)
}

View File

@ -107,7 +107,7 @@ func groupNotification(contentType int32, m proto.Message, sendID, groupID, recv
log.Info(operationID, utils.GetSelfFuncName(), "args: ", contentType, sendID, groupID, recvUserID)
var err error
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.Detail, err = proto.Marshal(m)
if err != nil {
log.Error(operationID, "Marshal failed ", err.Error(), m.String())
@ -212,8 +212,8 @@ func groupNotification(contentType int32, m proto.Message, sendID, groupID, recv
// 创建群后调用
func GroupCreatedNotification(operationID, opUserID, groupID string, initMemberList []string) {
GroupCreatedTips := sdkws.GroupCreatedTips{Group: &open_im_sdk.GroupInfo{},
OpUser: &open_im_sdk.GroupMemberFullInfo{}, GroupOwnerUser: &open_im_sdk.GroupMemberFullInfo{}}
GroupCreatedTips := sdkws.GroupCreatedTips{Group: &sdkws.GroupInfo{},
OpUser: &sdkws.GroupMemberFullInfo{}, GroupOwnerUser: &sdkws.GroupMemberFullInfo{}}
if err := setOpUserInfo(opUserID, groupID, GroupCreatedTips.OpUser); err != nil {
log.NewError(operationID, "setOpUserInfo failed ", err.Error(), opUserID, groupID, GroupCreatedTips.OpUser)
return
@ -229,7 +229,7 @@ func GroupCreatedNotification(operationID, opUserID, groupID string, initMemberL
return
}
for _, v := range initMemberList {
var groupMemberInfo open_im_sdk.GroupMemberFullInfo
var groupMemberInfo sdkws.GroupMemberFullInfo
if err := setGroupMemberInfo(groupID, v, &groupMemberInfo); err != nil {
log.Error(operationID, "setGroupMemberInfo failed ", err.Error(), groupID, v)
continue

View File

@ -4,21 +4,21 @@ import (
"Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func DeleteMessageNotification(opUserID, userID string, seqList []uint32, operationID string) {
DeleteMessageTips := open_im_sdk.DeleteMessageTips{OpUserID: opUserID, UserID: userID, SeqList: seqList}
DeleteMessageTips := sdkws.DeleteMessageTips{OpUserID: opUserID, UserID: userID, SeqList: seqList}
MessageNotification(operationID, userID, userID, constant.DeleteMessageNotification, &DeleteMessageTips)
}
func MessageNotification(operationID, sendID, recvID string, contentType int32, m proto.Message) {
log.Debug(operationID, utils.GetSelfFuncName(), "args: ", m.String(), contentType)
var err error
var tips open_im_sdk.TipsComm
var tips sdkws.TipsComm
tips.Detail, err = proto.Marshal(m)
if err != nil {
log.Error(operationID, "Marshal failed ", err.Error(), m.String())

View File

@ -1,43 +0,0 @@
package notification
import (
"Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
pbOffice "Open_IM/pkg/proto/office"
sdk "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
)
func WorkMomentSendNotification(operationID, recvID string, notificationMsg *pbOffice.WorkMomentNotificationMsg) {
log.NewInfo(operationID, utils.GetSelfFuncName(), recvID, notificationMsg)
WorkMomentNotification(operationID, recvID, recvID, notificationMsg)
}
func WorkMomentNotification(operationID, sendID, recvID string, m proto.Message) {
var tips sdk.TipsComm
var err error
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: false,
}
tips.JsonDetail, _ = marshaler.MarshalToString(m)
n := &msg.NotificationMsg{
SendID: sendID,
RecvID: recvID,
MsgFrom: constant.UserMsgType,
ContentType: constant.WorkMomentNotification,
SessionType: constant.SingleChatType,
OperationID: operationID,
}
n.Content, err = proto.Marshal(&tips)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "proto.Marshal failed")
return
}
log.NewInfo(operationID, utils.GetSelfFuncName(), string(n.Content))
msg.Notification(n)
}

View File

@ -10,7 +10,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
pbRtc "Open_IM/pkg/proto/rtc"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"github.com/golang/protobuf/proto"
)
@ -60,7 +60,7 @@ type SeqListData struct {
func (ws *WServer) argsValidate(m *Req, r int32, operationID string) (isPass bool, errCode int32, errMsg string, returnData interface{}) {
switch r {
case constant.WSGetNewestSeq:
data := open_im_sdk.GetMaxAndMinSeqReq{}
data := sdkws.GetMaxAndMinSeqReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.Error(operationID, "Decode Map struct err", err.Error(), r)
return false, 203, err.Error(), nil
@ -72,7 +72,7 @@ func (ws *WServer) argsValidate(m *Req, r int32, operationID string) (isPass boo
}
return true, 0, "", data
case constant.WSSendMsg:
data := open_im_sdk.MsgData{}
data := sdkws.MsgData{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.Error(operationID, "Decode Map struct err", err.Error(), r)
return false, 203, err.Error(), nil
@ -96,7 +96,7 @@ func (ws *WServer) argsValidate(m *Req, r int32, operationID string) (isPass boo
}
return true, 0, "", &data
case constant.WSPullMsgBySeqList:
data := open_im_sdk.PullMessageBySeqListReq{}
data := sdkws.PullMessageBySeqListReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.Error(operationID, "Decode Map struct err", err.Error(), r)
return false, 203, err.Error(), nil
@ -108,7 +108,7 @@ func (ws *WServer) argsValidate(m *Req, r int32, operationID string) (isPass boo
}
return true, 0, "", data
case constant.WsSetBackgroundStatus:
data := open_im_sdk.SetAppBackgroundStatusReq{}
data := sdkws.SetAppBackgroundStatusReq{}
if err := proto.Unmarshal(m.Data, &data); err != nil {
log.Error(operationID, "Decode Map struct err", err.Error(), r)
return false, 203, err.Error(), nil

View File

@ -1,547 +0,0 @@
package admincms
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/cache"
"Open_IM/pkg/common/db/controller"
"Open_IM/pkg/common/db/relation"
"Open_IM/pkg/common/log"
promePkg "Open_IM/pkg/common/prometheus"
"Open_IM/pkg/common/tokenverify"
"Open_IM/pkg/common/tracelog"
pbAdminCMS "Open_IM/pkg/proto/admin_cms"
common "Open_IM/pkg/proto/sdkws"
grpcPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"Open_IM/pkg/utils"
"context"
"errors"
"net"
"strconv"
"strings"
"sync"
"time"
"google.golang.org/grpc"
"gorm.io/gorm"
)
type adminCMSServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
adminCMSInterface controller.AdminCMSInterface
groupInterface controller.GroupInterface
userInterface controller.UserInterface
chatLogInterface controller.ChatLogInterface
}
func NewAdminCMSServer(port int) *adminCMSServer {
log.NewPrivateLog(constant.LogFileName)
admin := &adminCMSServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImAdminCMSName,
etcdSchema: config.Config.Zookeeper.Schema,
etcdAddr: config.Config.Zookeeper.ZkAddr,
}
var mysql relation.Mysql
var redis cache.RedisClient
mysql.InitConn()
redis.InitRedis()
admin.userInterface = controller.NewUserController(mysql.GormConn())
admin.groupInterface = controller.NewGroupInterface(mysql.GormConn(), redis.GetClient(), nil)
admin.adminCMSInterface = controller.NewAdminCMSController(mysql.GormConn())
admin.chatLogInterface = controller.NewChatLogController(mysql.GormConn())
return admin
}
func (s *adminCMSServer) Run() {
log.NewInfo("0", "AdminCMS rpc start ")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
var grpcOpts []grpc.ServerOption
if config.Config.Prometheus.Enable {
promePkg.NewGrpcRequestCounter()
promePkg.NewGrpcRequestFailedCounter()
promePkg.NewGrpcRequestSuccessCounter()
grpcOpts = append(grpcOpts, []grpc.ServerOption{
// grpc.UnaryInterceptor(promePkg.UnaryServerInterceptorProme),
grpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor),
grpc.UnaryInterceptor(grpcPrometheus.UnaryServerInterceptor),
}...)
}
srv := grpc.NewServer(grpcOpts...)
defer srv.GracefulStop()
//Service registers with etcd
pbAdminCMS.RegisterAdminCMSServer(srv, s)
rpcRegisterIP := config.Config.RpcRegisterIP
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
log.NewInfo("", "rpcRegisterIP ", rpcRegisterIP)
err = rpc.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10, "")
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
panic(utils.Wrap(err, "register admin module rpc to etcd err"))
}
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "message cms rpc success")
}
func (s *adminCMSServer) AdminLogin(ctx context.Context, req *pbAdminCMS.AdminLoginReq) (*pbAdminCMS.AdminLoginResp, error) {
resp := &pbAdminCMS.AdminLoginResp{}
for i, adminID := range config.Config.Manager.AppManagerUid {
if adminID == req.AdminID && config.Config.Manager.Secrets[i] == req.Secret {
token, expTime, err := tokenverify.CreateToken(adminID, constant.LinuxPlatformID)
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "generate token failed", "adminID: ", adminID, err.Error())
return nil, err
}
log.NewInfo(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "generate token success", "token: ", token, "expTime:", expTime)
resp.Token = token
break
}
}
if resp.Token == "" {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "failed")
return nil, constant.ErrInternalServer
}
admin, err := s.userInterface.Take(ctx, req.AdminID)
if err != nil {
return nil, err
}
resp.UserName = admin.Nickname
resp.FaceURL = admin.FaceURL
return resp, nil
}
func (s *adminCMSServer) GetUserToken(ctx context.Context, req *pbAdminCMS.GetUserTokenReq) (*pbAdminCMS.GetUserTokenResp, error) {
token, expTime, err := tokenverify.CreateToken(req.UserID, int(req.PlatformID))
if err != nil {
return nil, err
}
resp := &pbAdminCMS.GetUserTokenResp{Token: token, ExpTime: expTime}
return resp, nil
}
func (s *adminCMSServer) GetChatLogs(ctx context.Context, req *pbAdminCMS.GetChatLogsReq) (*pbAdminCMS.GetChatLogsResp, error) {
chatLog := relation.ChatLog{
Content: req.Content,
ContentType: req.ContentType,
SessionType: req.SessionType,
RecvID: req.RecvID,
SendID: req.SendID,
}
if req.SendTime != "" {
sendTime, err := utils.TimeStringToTime(req.SendTime)
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "time string parse error", err.Error())
return nil, err
}
chatLog.SendTime = sendTime
}
num, chatLogs, err := s.chatLogInterface.GetChatLog(&chatLog, req.Pagination.PageNumber, req.Pagination.ShowNumber, []int32{
constant.Text,
constant.Picture,
constant.Voice,
constant.Video,
constant.File,
constant.AtText,
constant.Merger,
constant.Card,
constant.Location,
constant.Custom,
constant.Revoke,
constant.Quote,
constant.AdvancedText,
constant.AdvancedRevoke,
constant.CustomNotTriggerConversation,
})
if err != nil {
return nil, err
}
resp := &pbAdminCMS.GetChatLogsResp{}
resp.ChatLogsNum = int32(num)
for _, chatLog := range chatLogs {
pbChatLog := &pbAdminCMS.ChatLog{}
utils.CopyStructFields(pbChatLog, chatLog)
pbChatLog.SendTime = chatLog.SendTime.Unix()
pbChatLog.CreateTime = chatLog.CreateTime.Unix()
if chatLog.SenderNickname == "" {
sendUser, err := s.userInterface.Take(ctx, chatLog.SendID)
if err != nil {
return nil, err
}
pbChatLog.SenderNickname = sendUser.Nickname
}
switch chatLog.SessionType {
case constant.SingleChatType:
recvUser, err := s.userInterface.Take(ctx, chatLog.RecvID)
if err != nil {
return nil, err
}
pbChatLog.SenderNickname = recvUser.Nickname
case constant.GroupChatType, constant.SuperGroupChatType:
group, err := s.groupInterface.TakeGroup(ctx, chatLog.RecvID)
if err != nil {
return nil, err
}
pbChatLog.RecvID = group.GroupID
pbChatLog.GroupName = group.GroupName
}
resp.ChatLogs = append(resp.ChatLogs, pbChatLog)
}
return resp, nil
}
func (s *adminCMSServer) GetActiveGroup(_ context.Context, req *pbAdminCMS.GetActiveGroupReq) (*pbAdminCMS.GetActiveGroupResp, error) {
resp := &pbAdminCMS.GetActiveGroupResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
return nil, err
}
activeGroups, err := s.adminCMSInterface.GetActiveGroups(fromTime, toTime, 12)
if err != nil {
return nil, err
}
for _, activeGroup := range activeGroups {
resp.Groups = append(resp.Groups,
&pbAdminCMS.GroupResp{
GroupName: activeGroup.Name,
GroupID: activeGroup.ID,
MessageNum: int32(activeGroup.MessageNum),
})
}
return resp, nil
}
func (s *adminCMSServer) GetActiveUser(ctx context.Context, req *pbAdminCMS.GetActiveUserReq) (*pbAdminCMS.GetActiveUserResp, error) {
resp := &pbAdminCMS.GetActiveUserResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return nil, err
}
activeUsers, err := s.adminCMSInterface.GetActiveUsers(fromTime, toTime, 12)
if err != nil {
return nil, err
}
for _, activeUser := range activeUsers {
resp.Users = append(resp.Users,
&pbAdminCMS.UserResp{
UserID: activeUser.ID,
NickName: activeUser.Name,
MessageNum: int32(activeUser.MessageNum),
},
)
}
return resp, nil
}
func ParseTimeFromTo(from, to string) (time.Time, time.Time, error) {
var fromTime time.Time
var toTime time.Time
fromTime, err := utils.TimeStringToTime(from)
if err != nil {
return fromTime, toTime, err
}
toTime, err = utils.TimeStringToTime(to)
if err != nil {
return fromTime, toTime, err
}
return fromTime, toTime, nil
}
func isInOneMonth(from, to time.Time) bool {
return from.Month() == to.Month() && from.Year() == to.Year()
}
func GetRangeDate(from, to time.Time) [][2]time.Time {
interval := to.Sub(from)
var times [][2]time.Time
switch {
// today
case interval == 0:
times = append(times, [2]time.Time{
from, from.Add(time.Hour * 24),
})
// days
case isInOneMonth(from, to):
for i := 0; ; i++ {
fromTime := from.Add(time.Hour * 24 * time.Duration(i))
toTime := from.Add(time.Hour * 24 * time.Duration(i+1))
if toTime.After(to.Add(time.Hour * 24)) {
break
}
times = append(times, [2]time.Time{
fromTime, toTime,
})
}
// month
case !isInOneMonth(from, to):
if to.Sub(from) < time.Hour*24*30 {
for i := 0; ; i++ {
fromTime := from.Add(time.Hour * 24 * time.Duration(i))
toTime := from.Add(time.Hour * 24 * time.Duration(i+1))
if toTime.After(to.Add(time.Hour * 24)) {
break
}
times = append(times, [2]time.Time{
fromTime, toTime,
})
}
} else {
for i := 0; ; i++ {
if i == 0 {
fromTime := from
toTime := getFirstDateOfNextNMonth(fromTime, 1)
times = append(times, [2]time.Time{
fromTime, toTime,
})
} else {
fromTime := getFirstDateOfNextNMonth(from, i)
toTime := getFirstDateOfNextNMonth(fromTime, 1)
if toTime.After(to) {
toTime = to
times = append(times, [2]time.Time{
fromTime, toTime,
})
break
}
times = append(times, [2]time.Time{
fromTime, toTime,
})
}
}
}
}
return times
}
func getFirstDateOfNextNMonth(currentTime time.Time, n int) time.Time {
lastOfMonth := time.Date(currentTime.Year(), currentTime.Month(), 1, 0, 0, 0, 0, currentTime.Location()).AddDate(0, n, 0)
return lastOfMonth
}
func (s *adminCMSServer) GetGroupStatistics(ctx context.Context, req *pbAdminCMS.GetGroupStatisticsReq) (*pbAdminCMS.GetGroupStatisticsResp, error) {
resp := &pbAdminCMS.GetGroupStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
return nil, err
}
increaseGroupNum, err := s.adminCMSInterface.GetIncreaseGroupNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
return nil, err
}
totalGroupNum, err := s.adminCMSInterface.GetTotalGroupNum()
if err != nil {
return nil, err
}
resp.IncreaseGroupNum = int32(increaseGroupNum)
resp.TotalGroupNum = int32(totalGroupNum)
times := GetRangeDate(fromTime, toTime)
wg := &sync.WaitGroup{}
resp.IncreaseGroupNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
resp.TotalGroupNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
wg.Add(len(times))
for i, v := range times {
go func(wg *sync.WaitGroup, index int, v [2]time.Time) {
defer wg.Done()
num, err := s.adminCMSInterface.GetIncreaseGroupNum(v[0], v[1])
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.IncreaseGroupNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
num, err = s.adminCMSInterface.GetGroupNum(v[1])
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.TotalGroupNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}
func (s *adminCMSServer) GetMessageStatistics(ctx context.Context, req *pbAdminCMS.GetMessageStatisticsReq) (*pbAdminCMS.GetMessageStatisticsResp, error) {
resp := &pbAdminCMS.GetMessageStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
log.NewDebug(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "times: ", fromTime, toTime)
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return nil, err
}
privateMessageNum, err := s.adminCMSInterface.GetSingleChatMessageNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
return nil, err
}
groupMessageNum, err := s.adminCMSInterface.GetGroupMessageNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
return nil, err
}
log.NewDebug(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), privateMessageNum, groupMessageNum)
resp.PrivateMessageNum = int32(privateMessageNum)
resp.GroupMessageNum = int32(groupMessageNum)
times := GetRangeDate(fromTime, toTime)
resp.GroupMessageNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
resp.PrivateMessageNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
wg := &sync.WaitGroup{}
wg.Add(len(times))
for i, v := range times {
go func(wg *sync.WaitGroup, index int, v [2]time.Time) {
defer wg.Done()
num, err := s.adminCMSInterface.GetSingleChatMessageNum(v[0], v[1])
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.PrivateMessageNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
num, err = s.adminCMSInterface.GetGroupMessageNum(v[0], v[1])
if err != nil {
log.NewError(tracelog.GetOperationID(ctx), utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.GroupMessageNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}
func (s *adminCMSServer) GetUserStatistics(_ context.Context, req *pbAdminCMS.GetUserStatisticsReq) (*pbAdminCMS.GetUserStatisticsResp, error) {
resp := &pbAdminCMS.GetUserStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo failed", err.Error())
return nil, err
}
activeUserNum, err := s.adminCMSInterface.GetActiveUserNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
return nil, err
}
increaseUserNum, err := s.adminCMSInterface.GetIncreaseUserNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
return nil, err
}
totalUserNum, err := s.adminCMSInterface.GetTotalUserNum()
if err != nil {
return nil, err
}
resp.ActiveUserNum = int32(activeUserNum)
resp.TotalUserNum = int32(totalUserNum)
resp.IncreaseUserNum = int32(increaseUserNum)
times := GetRangeDate(fromTime, toTime)
resp.TotalUserNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
resp.ActiveUserNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
resp.IncreaseUserNumList = make([]*pbAdminCMS.DateNumList, len(times), len(times))
wg := &sync.WaitGroup{}
wg.Add(len(times))
for i, v := range times {
go func(wg *sync.WaitGroup, index int, v [2]time.Time) {
defer wg.Done()
num, err := s.adminCMSInterface.GetActiveUserNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.ActiveUserNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
num, err = s.adminCMSInterface.GetTotalUserNumByDate(v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTotalUserNumByDate", v, err.Error())
}
resp.TotalUserNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
num, err = s.adminCMSInterface.GetIncreaseUserNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseUserNum", v, err.Error())
}
resp.IncreaseUserNumList[index] = &pbAdminCMS.DateNumList{
Date: v[0].String(),
Num: int32(num),
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}
func (s *adminCMSServer) GetUserFriends(ctx context.Context, req *pbAdminCMS.GetUserFriendsReq) (*pbAdminCMS.GetUserFriendsResp, error) {
resp := &pbAdminCMS.GetUserFriendsResp{}
var friendList []*relation.FriendUser
var err error
if req.FriendUserID != "" {
friend, err := s.adminCMSInterface.GetFriendByIDCMS(req.UserID, req.FriendUserID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return resp, nil
}
return nil, err
}
friendList = append(friendList, friend)
resp.FriendNums = 1
} else {
var count int64
friendList, count, err = s.adminCMSInterface.GetUserFriendsCMS(req.UserID, req.FriendUserName, req.Pagination.PageNumber, req.Pagination.ShowNumber)
if err != nil {
return nil, err
}
resp.FriendNums = int32(count)
}
for _, v := range friendList {
friendInfo := &common.FriendInfo{}
userInfo := &common.UserInfo{UserID: v.FriendUserID, Nickname: v.Nickname}
utils.CopyStructFields(friendInfo, v)
friendInfo.FriendUser = userInfo
resp.FriendInfoList = append(resp.FriendInfoList, friendInfo)
}
return resp, nil
}
func (s *adminCMSServer) GetUserIDByEmailAndPhoneNumber(ctx context.Context, req *pbAdminCMS.GetUserIDByEmailAndPhoneNumberReq) (*pbAdminCMS.GetUserIDByEmailAndPhoneNumberResp, error) {
resp := &pbAdminCMS.GetUserIDByEmailAndPhoneNumberResp{}
userIDList, err := s.userInterface.GetUserIDsByEmailAndID(req.PhoneNumber, req.Email)
if err != nil {
return resp, nil
}
resp.UserIDList = userIDList
return resp, nil
}

View File

@ -2,15 +2,18 @@ package conversation
import (
"Open_IM/internal/common/check"
chat "Open_IM/internal/common/notification"
chat "Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/cache"
"Open_IM/pkg/common/db/controller"
"Open_IM/pkg/common/db/relation"
"Open_IM/pkg/common/db/table"
tableRelation "Open_IM/pkg/common/db/table/relation"
"Open_IM/pkg/common/db/unrelation"
"Open_IM/pkg/common/log"
promePkg "Open_IM/pkg/common/prometheus"
"Open_IM/pkg/getcdv3"
pbConversation "Open_IM/pkg/proto/conversation"
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"github.com/dtm-labs/rockscache"
@ -47,7 +50,7 @@ func NewConversationServer(port int) *conversationServer {
var cCache cache.ConversationCache
//mysql init
var mysql relation.Mysql
err := mysql.InitConn().AutoMigrateModel(&table.ConversationModel{})
err := mysql.InitConn().AutoMigrateModel(&tableRelation.ConversationModel{})
if err != nil {
panic("db init err:" + err.Error())
}
@ -170,7 +173,7 @@ func (c *conversationServer) GetConversations(ctx context.Context, req *pbConver
func (c *conversationServer) BatchSetConversations(ctx context.Context, req *pbConversation.BatchSetConversationsReq) (*pbConversation.BatchSetConversationsResp, error) {
resp := &pbConversation.BatchSetConversationsResp{}
var conversations []*table.ConversationModel
var conversations []*tableRelation.ConversationModel
if err := utils.CopyStructFields(&conversations, req.Conversations); err != nil {
return nil, err
}
@ -203,16 +206,16 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
return nil, err
}
}
var conversation table.ConversationModel
var conversation tableRelation.ConversationModel
if err := utils.CopyStructFields(&conversation, req.Conversation); err != nil {
return nil, err
}
if req.FieldType == constant.FieldIsPrivateChat {
err := c.ConversationInterface.SyncPeerUserPrivateConversationTx(ctx, req.Conversation)
err := c.ConversationInterface.SyncPeerUserPrivateConversationTx(ctx, &conversation)
if err != nil {
return nil, err
}
chat.ConversationSetPrivateNotification(req.OperationID, req.Conversation.OwnerUserID, req.Conversation.UserID, req.Conversation.IsPrivateChat)
chat.ConversationSetPrivateNotification(ctx, req.Conversation.OwnerUserID, req.Conversation.UserID, req.Conversation.IsPrivateChat)
return resp, nil
}
//haveUserID, err := c.ConversationInterface.GetUserIDExistConversation(ctx, req.UserIDList, req.Conversation.ConversationID)
@ -239,29 +242,18 @@ func (c *conversationServer) ModifyConversationField(ctx context.Context, req *p
case constant.FieldBurnDuration:
filedMap["burn_duration"] = req.Conversation.BurnDuration
}
c.ConversationInterface.SetUsersConversationFiledTx(ctx, req.UserIDList, &conversation, filedMap)
err = c.ConversationInterface.UpdateUsersConversationFiled(ctx, haveUserID, req.Conversation.ConversationID, filedMap)
if err != nil {
return nil, err
}
var conversations []*pbConversation.Conversation
for _, v := range utils.DifferenceString(haveUserID, req.UserIDList) {
temp := new(pbConversation.Conversation)
_ = utils.CopyStructFields(temp, req.Conversation)
temp.OwnerUserID = v
conversations = append(conversations, temp)
}
err = c.ConversationInterface.CreateConversation(ctx, conversations)
err = c.ConversationInterface.SetUsersConversationFiledTx(ctx, req.UserIDList, &conversation, filedMap)
if err != nil {
return nil, err
}
if isSyncConversation {
for _, v := range req.UserIDList {
chat.ConversationChangeNotification(req.OperationID, v)
chat.ConversationChangeNotification(ctx, v)
}
} else {
for _, v := range req.UserIDList {
chat.ConversationUnreadChangeNotification(req.OperationID, v, req.Conversation.ConversationID, req.Conversation.UpdateUnreadCountTime)
chat.ConversationUnreadChangeNotification(ctx, v, req.Conversation.ConversationID, req.Conversation.UpdateUnreadCountTime)
}
}
return resp, nil

View File

@ -1,92 +1,105 @@
package group
import (
cbApi "Open_IM/pkg/callbackstruct"
"Open_IM/pkg/apistruct"
"Open_IM/pkg/callbackstruct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/table/relation"
"Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tracelog"
pbGroup "Open_IM/pkg/proto/group"
"Open_IM/pkg/proto/group"
"Open_IM/pkg/utils"
"context"
"google.golang.org/protobuf/types/known/wrapperspb"
)
func callbackBeforeCreateGroup(ctx context.Context, req *pbGroup.CreateGroupReq) (err error) {
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", req)
}()
func CallbackBeforeCreateGroup(ctx context.Context, req *group.CreateGroupReq) (err error) {
if !config.Config.Callback.CallbackBeforeCreateGroup.Enable {
return nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), req.String())
commonCallbackReq := &cbApi.CallbackBeforeCreateGroupReq{
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", req)
}()
operationID := tracelog.GetOperationID(ctx)
commonCallbackReq := &callbackstruct.CallbackBeforeCreateGroupReq{
CallbackCommand: constant.CallbackBeforeCreateGroupCommand,
OperationID: req.OperationID,
OperationID: operationID,
GroupInfo: *req.GroupInfo,
InitMemberList: req.InitMemberList,
}
callbackResp := cbApi.CommonCallbackResp{OperationID: req.OperationID}
resp := &cbApi.CallbackBeforeCreateGroupResp{
CommonCallbackResp: &callbackResp,
commonCallbackReq.InitMemberList = append(commonCallbackReq.InitMemberList, &apistruct.GroupAddMemberInfo{
UserID: req.OwnerUserID,
RoleLevel: constant.GroupOwner,
})
for _, userID := range req.AdminUserIDs {
commonCallbackReq.InitMemberList = append(commonCallbackReq.InitMemberList, &apistruct.GroupAddMemberInfo{
UserID: userID,
RoleLevel: constant.GroupAdmin,
})
}
//utils.CopyStructFields(req, msg.MsgData)
defer log.NewDebug(req.OperationID, utils.GetSelfFuncName(), commonCallbackReq, *resp)
err = http.CallBackPostReturn(config.Config.Callback.CallbackUrl, constant.CallbackBeforeCreateGroupCommand, commonCallbackReq,
resp, config.Config.Callback.CallbackBeforeCreateGroup)
if err == nil {
if resp.GroupID != nil {
req.GroupInfo.GroupID = *resp.GroupID
}
if resp.GroupName != nil {
req.GroupInfo.GroupName = *resp.GroupName
}
if resp.Notification != nil {
req.GroupInfo.Notification = *resp.Notification
}
if resp.Introduction != nil {
req.GroupInfo.Introduction = *resp.Introduction
}
if resp.FaceURL != nil {
req.GroupInfo.FaceURL = *resp.FaceURL
}
if resp.OwnerUserID != nil {
req.GroupInfo.OwnerUserID = *resp.OwnerUserID
}
if resp.Ex != nil {
req.GroupInfo.Ex = *resp.Ex
}
if resp.Status != nil {
req.GroupInfo.Status = *resp.Status
}
if resp.CreatorUserID != nil {
req.GroupInfo.CreatorUserID = *resp.CreatorUserID
}
if resp.GroupType != nil {
req.GroupInfo.GroupType = *resp.GroupType
}
if resp.NeedVerification != nil {
req.GroupInfo.NeedVerification = *resp.NeedVerification
}
if resp.LookMemberInfo != nil {
req.GroupInfo.LookMemberInfo = *resp.LookMemberInfo
}
for _, userID := range req.AdminUserIDs {
commonCallbackReq.InitMemberList = append(commonCallbackReq.InitMemberList, &apistruct.GroupAddMemberInfo{
UserID: userID,
RoleLevel: constant.GroupOrdinaryUsers,
})
}
return err
resp := &callbackstruct.CallbackBeforeCreateGroupResp{
CommonCallbackResp: &callbackstruct.CommonCallbackResp{OperationID: operationID},
}
err = http.CallBackPostReturn(config.Config.Callback.CallbackUrl, constant.CallbackBeforeCreateGroupCommand, commonCallbackReq, resp, config.Config.Callback.CallbackBeforeCreateGroup)
if err != nil {
return err
}
if resp.GroupID != nil {
req.GroupInfo.GroupID = *resp.GroupID
}
if resp.GroupName != nil {
req.GroupInfo.GroupName = *resp.GroupName
}
if resp.Notification != nil {
req.GroupInfo.Notification = *resp.Notification
}
if resp.Introduction != nil {
req.GroupInfo.Introduction = *resp.Introduction
}
if resp.FaceURL != nil {
req.GroupInfo.FaceURL = *resp.FaceURL
}
if resp.OwnerUserID != nil {
req.GroupInfo.OwnerUserID = *resp.OwnerUserID
}
if resp.Ex != nil {
req.GroupInfo.Ex = *resp.Ex
}
if resp.Status != nil {
req.GroupInfo.Status = *resp.Status
}
if resp.CreatorUserID != nil {
req.GroupInfo.CreatorUserID = *resp.CreatorUserID
}
if resp.GroupType != nil {
req.GroupInfo.GroupType = *resp.GroupType
}
if resp.NeedVerification != nil {
req.GroupInfo.NeedVerification = *resp.NeedVerification
}
if resp.LookMemberInfo != nil {
req.GroupInfo.LookMemberInfo = *resp.LookMemberInfo
}
return nil
}
func CallbackBeforeMemberJoinGroup(ctx context.Context, operationID string, groupMember *relation.GroupMemberModel, groupEx string) (err error) {
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "groupMember", *groupMember, "groupEx", groupEx)
}()
callbackResp := cbApi.CommonCallbackResp{OperationID: operationID}
func CallbackBeforeMemberJoinGroup(ctx context.Context, groupMember *relation.GroupMemberModel, groupEx string) (err error) {
if !config.Config.Callback.CallbackBeforeMemberJoinGroup.Enable {
return nil
}
log.NewDebug(operationID, "args: ", *groupMember)
callbackReq := cbApi.CallbackBeforeMemberJoinGroupReq{
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "groupMember", *groupMember, "groupEx", groupEx)
}()
operationID := tracelog.GetOperationID(ctx)
callbackResp := callbackstruct.CommonCallbackResp{OperationID: operationID}
callbackReq := callbackstruct.CallbackBeforeMemberJoinGroupReq{
CallbackCommand: constant.CallbackBeforeMemberJoinGroupCommand,
OperationID: operationID,
GroupID: groupMember.GroupID,
@ -94,42 +107,44 @@ func CallbackBeforeMemberJoinGroup(ctx context.Context, operationID string, grou
Ex: groupMember.Ex,
GroupEx: groupEx,
}
resp := &cbApi.CallbackBeforeMemberJoinGroupResp{
resp := &callbackstruct.CallbackBeforeMemberJoinGroupResp{
CommonCallbackResp: &callbackResp,
}
err = http.CallBackPostReturn(config.Config.Callback.CallbackUrl, constant.CallbackBeforeMemberJoinGroupCommand, callbackReq,
resp, config.Config.Callback.CallbackBeforeMemberJoinGroup)
if err == nil {
if resp.MuteEndTime != nil {
groupMember.MuteEndTime = utils.UnixSecondToTime(*resp.MuteEndTime)
}
if resp.FaceURL != nil {
groupMember.FaceURL = *resp.FaceURL
}
if resp.Ex != nil {
groupMember.Ex = *resp.Ex
}
if resp.NickName != nil {
groupMember.Nickname = *resp.NickName
}
if resp.RoleLevel != nil {
groupMember.RoleLevel = *resp.RoleLevel
}
if err != nil {
return err
}
return err
if resp.MuteEndTime != nil {
groupMember.MuteEndTime = utils.UnixSecondToTime(*resp.MuteEndTime)
}
if resp.FaceURL != nil {
groupMember.FaceURL = *resp.FaceURL
}
if resp.Ex != nil {
groupMember.Ex = *resp.Ex
}
if resp.NickName != nil {
groupMember.Nickname = *resp.NickName
}
if resp.RoleLevel != nil {
groupMember.RoleLevel = *resp.RoleLevel
}
return nil
}
func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGroupMemberInfo) (err error) {
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", *req)
}()
callbackResp := cbApi.CommonCallbackResp{OperationID: req.OperationID}
func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *group.SetGroupMemberInfo) (err error) {
if !config.Config.Callback.CallbackBeforeSetGroupMemberInfo.Enable {
return nil
}
callbackReq := cbApi.CallbackBeforeSetGroupMemberInfoReq{
defer func() {
tracelog.SetCtxInfo(ctx, utils.GetFuncName(1), err, "req", *req)
}()
operationID := tracelog.GetOperationID(ctx)
callbackResp := callbackstruct.CommonCallbackResp{OperationID: operationID}
callbackReq := callbackstruct.CallbackBeforeSetGroupMemberInfoReq{
CallbackCommand: constant.CallbackBeforeSetGroupMemberInfoCommand,
OperationID: req.OperationID,
OperationID: operationID,
GroupID: req.GroupID,
UserID: req.UserID,
}
@ -145,24 +160,24 @@ func CallbackBeforeSetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGroup
if req.Ex != nil {
callbackReq.Ex = req.Ex.Value
}
resp := &cbApi.CallbackBeforeSetGroupMemberInfoResp{
resp := &callbackstruct.CallbackBeforeSetGroupMemberInfoResp{
CommonCallbackResp: &callbackResp,
}
err = http.CallBackPostReturn(config.Config.Callback.CallbackUrl, constant.CallbackBeforeSetGroupMemberInfoCommand, callbackReq,
resp, config.Config.Callback.CallbackBeforeSetGroupMemberInfo.CallbackTimeOut, &config.Config.Callback.CallbackBeforeSetGroupMemberInfo.CallbackFailedContinue)
if err == nil {
if resp.FaceURL != nil {
req.FaceURL = &wrapperspb.StringValue{Value: *resp.FaceURL}
}
if resp.Nickname != nil {
req.Nickname = &wrapperspb.StringValue{Value: *resp.Nickname}
}
if resp.RoleLevel != nil {
req.RoleLevel = &wrapperspb.Int32Value{Value: *resp.RoleLevel}
}
if resp.Ex != nil {
req.Ex = &wrapperspb.StringValue{Value: *resp.Ex}
}
err = http.CallBackPostReturn(config.Config.Callback.CallbackUrl, constant.CallbackBeforeSetGroupMemberInfoCommand, callbackReq, resp, config.Config.Callback.CallbackBeforeSetGroupMemberInfo)
if err != nil {
return err
}
if resp.FaceURL != nil {
req.FaceURL = &wrapperspb.StringValue{Value: *resp.FaceURL}
}
if resp.Nickname != nil {
req.Nickname = &wrapperspb.StringValue{Value: *resp.Nickname}
}
if resp.RoleLevel != nil {
req.RoleLevel = &wrapperspb.Int32Value{Value: *resp.RoleLevel}
}
if resp.Ex != nil {
req.Ex = &wrapperspb.StringValue{Value: *resp.Ex}
}
return err
}

View File

@ -3,12 +3,12 @@ package group
import (
"Open_IM/pkg/common/db/table/relation"
pbGroup "Open_IM/pkg/proto/group"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"time"
)
func DbToPbGroupInfo(m *relation.GroupModel, ownerUserID string, memberCount uint32) *open_im_sdk.GroupInfo {
return &open_im_sdk.GroupInfo{
func DbToPbGroupInfo(m *relation.GroupModel, ownerUserID string, memberCount uint32) *sdkws.GroupInfo {
return &sdkws.GroupInfo{
GroupID: m.GroupID,
GroupName: m.GroupName,
Notification: m.Notification,
@ -48,8 +48,8 @@ func DbToPbCMSGroup(m *relation.GroupModel, ownerUserID string, ownerUserName st
}
}
func DbToPbGroupMembersCMSResp(m *relation.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
return &open_im_sdk.GroupMemberFullInfo{
func DbToPbGroupMembersCMSResp(m *relation.GroupMemberModel) *sdkws.GroupMemberFullInfo {
return &sdkws.GroupMemberFullInfo{
GroupID: m.GroupID,
UserID: m.UserID,
RoleLevel: m.RoleLevel,
@ -65,8 +65,8 @@ func DbToPbGroupMembersCMSResp(m *relation.GroupMemberModel) *open_im_sdk.GroupM
}
}
func DbToPbGroupRequest(m *relation.GroupRequestModel, user *open_im_sdk.PublicUserInfo, group *open_im_sdk.GroupInfo) *open_im_sdk.GroupRequest {
return &open_im_sdk.GroupRequest{
func DbToPbGroupRequest(m *relation.GroupRequestModel, user *sdkws.PublicUserInfo, group *sdkws.GroupInfo) *sdkws.GroupRequest {
return &sdkws.GroupRequest{
UserInfo: user,
GroupInfo: group,
HandleResult: m.HandleResult,
@ -89,7 +89,7 @@ func DbToPbGroupAbstractInfo(groupID string, groupMemberNumber uint32, groupMemb
}
}
func PbToDBGroupInfo(m *open_im_sdk.GroupInfo) *relation.GroupModel {
func PbToDBGroupInfo(m *sdkws.GroupInfo) *relation.GroupModel {
return &relation.GroupModel{
GroupID: m.GroupID,
GroupName: m.GroupName,
@ -109,7 +109,7 @@ func PbToDBGroupInfo(m *open_im_sdk.GroupInfo) *relation.GroupModel {
}
}
func PbToDbGroupMember(m *open_im_sdk.UserInfo) *relation.GroupMemberModel {
func PbToDbGroupMember(m *sdkws.UserInfo) *relation.GroupMemberModel {
return &relation.GroupMemberModel{
UserID: m.UserID,
Nickname: m.Nickname,

View File

@ -2,11 +2,11 @@ package group
import (
pbGroup "Open_IM/pkg/proto/group"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
"time"
)
func UpdateGroupInfoMap(group *open_im_sdk.GroupInfoForSet) map[string]any {
func UpdateGroupInfoMap(group *sdkws.GroupInfoForSet) map[string]any {
m := make(map[string]any)
if group.GroupName != "" {
m["group_name"] = group.GroupName

View File

@ -1,94 +0,0 @@
package group
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/tracelog"
pbConversation "Open_IM/pkg/proto/conversation"
sdkws "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"errors"
"math/big"
"strconv"
"strings"
"time"
)
func GetPublicUserInfoOne(ctx context.Context, userID string) (*sdkws.PublicUserInfo, error) {
return nil, errors.New("todo")
}
func GetUsersInfo(ctx context.Context, userIDs []string) ([]*sdkws.UserInfo, error) {
return nil, errors.New("todo")
}
func GetUserInfoMap(ctx context.Context, userIDs []string) (map[string]*sdkws.UserInfo, error) {
users, err := GetUsersInfo(ctx, userIDs)
if err != nil {
return nil, err
}
return utils.SliceToMap(users, func(e *sdkws.UserInfo) string {
return e.UserID
}), nil
}
func GetPublicUserInfo(ctx context.Context, userIDs []string) ([]*sdkws.PublicUserInfo, error) {
return nil, errors.New("todo")
}
func GetPublicUserInfoMap(ctx context.Context, userIDs []string) (map[string]*sdkws.PublicUserInfo, error) {
users, err := GetPublicUserInfo(ctx, userIDs)
if err != nil {
return nil, err
}
return utils.SliceToMap(users, func(e *sdkws.PublicUserInfo) string {
return e.UserID
}), nil
}
func GetUsername(ctx context.Context, userIDs []string) (map[string]string, error) {
if len(userIDs) == 0 {
return map[string]string{}, nil
}
users, err := GetPublicUserInfo(ctx, userIDs)
if err != nil {
return nil, err
}
if ids := utils.Single(userIDs, utils.Slice(users, func(e *sdkws.PublicUserInfo) string {
return e.UserID
})); len(ids) > 0 {
return nil, constant.ErrUserIDNotFound.Wrap(strings.Join(ids, ","))
}
return utils.SliceToMapAny(users, func(e *sdkws.PublicUserInfo) (string, string) {
return e.UserID, e.Nickname
}), nil
}
func GroupNotification(ctx context.Context, groupID string) {
var conversationReq pbConversation.ModifyConversationFieldReq
conversation := pbConversation.Conversation{
OwnerUserID: tracelog.GetOpUserID(ctx),
ConversationID: utils.GetConversationIDBySessionType(groupID, constant.GroupChatType),
ConversationType: constant.GroupChatType,
GroupID: groupID,
}
conversationReq.Conversation = &conversation
conversationReq.OperationID = tracelog.GetOperationID(ctx)
conversationReq.FieldType = constant.FieldGroupAtType
conversation.GroupAtType = constant.GroupNotification
conversationReq.UserIDList = cacheResp.UserIDList
_, err = pbConversation.NewConversationClient(s.etcdConn.GetConn("", config.Config.RpcRegisterName.OpenImConversationName)).ModifyConversationField(ctx, &conversationReq)
tracelog.SetCtxInfo(ctx, "ModifyConversationField", err, "req", &conversationReq, "resp", conversationReply)
}
func genGroupID(ctx context.Context, groupID string) string {
if groupID != "" {
return groupID
}
groupID = utils.Md5(tracelog.GetOperationID(ctx) + strconv.FormatInt(time.Now().UnixNano(), 10))
bi := big.NewInt(0)
bi.SetString(groupID[0:8], 16)
groupID = bi.String()
return groupID
}

View File

@ -1,8 +1,9 @@
package group
import (
"Open_IM/internal/common/check"
"Open_IM/internal/common/network"
"Open_IM/internal/common/notification"
chat "Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/cache"
@ -17,11 +18,14 @@ import (
"Open_IM/pkg/common/tracelog"
discoveryRegistry "Open_IM/pkg/discoveryregistry"
pbGroup "Open_IM/pkg/proto/group"
open_im_sdk "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"fmt"
grpcPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"gorm.io/gorm"
"math/big"
"math/rand"
"net"
"strconv"
"strings"
@ -38,6 +42,7 @@ type groupServer struct {
zkAddr []string
GroupInterface controller.GroupInterface
registerCenter discoveryRegistry.SvcDiscoveryRegistry
user *check.UserCheck
}
func NewGroupServer(port int) *groupServer {
@ -72,8 +77,8 @@ func NewGroupServer(port int) *groupServer {
}
//conns, err := g.registerCenter.GetConns(config.Config.RpcRegisterName.OpenImConversationName)
g.GroupInterface = controller.NewGroupInterface(mysql.GormConn(), redis.GetClient(), mongo.GetClient())
g.user = check.NewUserCheck()
return &g
}
@ -132,8 +137,71 @@ func (s *groupServer) CheckGroupAdmin(ctx context.Context, groupID string) error
return nil
}
func (s *groupServer) GetUsernameMap(ctx context.Context, userIDs []string, complete bool) (map[string]string, error) {
if len(userIDs) == 0 {
return map[string]string{}, nil
}
users, err := s.user.GetPublicUserInfos(ctx, userIDs, complete)
if err != nil {
return nil, err
}
return utils.SliceToMapAny(users, func(e *open_im_sdk.PublicUserInfo) (string, string) {
return e.UserID, e.Nickname
}), nil
}
func (s *groupServer) GroupNotification(ctx context.Context, groupID string) {
// todo 群公告修改通知
//var conversationReq pbConversation.ModifyConversationFieldReq
//conversation := pbConversation.Conversation{
// OwnerUserID: tracelog.GetOpUserID(ctx),
// ConversationID: utils.GetConversationIDBySessionType(groupID, constant.GroupChatType),
// ConversationType: constant.GroupChatType,
// GroupID: groupID,
//}
//conversationReq.Conversation = &conversation
//conversationReq.FieldType = constant.FieldGroupAtType
//conversation.GroupAtType = constant.GroupNotification
//conversationReq.UserIDList = userIDs
//_, err := pbConversation.NewConversationClient(s.etcdConn.GetConn("", config.Config.RpcRegisterName.OpenImConversationName)).ModifyConversationField(ctx, &conversationReq)
//tracelog.SetCtxInfo(ctx, "ModifyConversationField", err, "req", &conversationReq, "resp", conversationReply)
}
func (s *groupServer) IsNotFound(err error) bool {
return utils.Unwrap(err) == gorm.ErrRecordNotFound
}
func (s *groupServer) GenGroupID(ctx context.Context, groupID *string) error {
if *groupID != "" {
_, err := s.GroupInterface.TakeGroup(ctx, *groupID)
if err == nil {
return constant.ErrGroupIDExisted.Wrap("group id existed " + *groupID)
} else if s.IsNotFound(err) {
return nil
} else {
return err
}
}
for i := 0; i < 10; i++ {
id := utils.Md5(strings.Join([]string{tracelog.GetOperationID(ctx), strconv.FormatInt(time.Now().UnixNano(), 10), strconv.Itoa(rand.Int())}, ",;,"))
bi := big.NewInt(0)
bi.SetString(id[0:8], 16)
id = bi.String()
_, err := s.GroupInterface.TakeGroup(ctx, id)
if err == nil {
continue
} else if s.IsNotFound(err) {
*groupID = id
return nil
} else {
return err
}
}
return constant.ErrData.Wrap("group id gen error")
}
func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupReq) (*pbGroup.CreateGroupResp, error) {
resp := &pbGroup.CreateGroupResp{GroupInfo: &open_im_sdk.GroupInfo{}}
resp := &pbGroup.CreateGroupResp{GroupInfo: &sdkws.GroupInfo{}}
if err := tokenverify.CheckAccessV3(ctx, req.OwnerUserID); err != nil {
return nil, err
}
@ -144,19 +212,18 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
if utils.Duplicate(userIDs) {
return nil, constant.ErrArgs.Wrap("group member repeated")
}
userMap, err := GetUserInfoMap(ctx, userIDs)
userMap, err := s.user.GetUsersInfoMap(ctx, userIDs, true)
if err != nil {
return nil, err
}
if ids := utils.Single(userIDs, utils.Keys(userMap)); len(ids) > 0 {
return nil, constant.ErrUserIDNotFound.Wrap(strings.Join(ids, ","))
}
if err := callbackBeforeCreateGroup(ctx, req); err != nil {
if err := CallbackBeforeCreateGroup(ctx, req); err != nil {
return nil, err
}
var groupMembers []*relationTb.GroupMemberModel
group := PbToDBGroupInfo(req.GroupInfo)
group.GroupID = genGroupID(ctx, req.GroupInfo.GroupID)
if err := s.GenGroupID(ctx, &group.GroupID); err != nil {
return nil, err
}
joinGroup := func(userID string, roleLevel int32) error {
groupMember := PbToDbGroupMember(userMap[userID])
groupMember.Nickname = ""
@ -165,7 +232,7 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
groupMember.OperatorUserID = tracelog.GetOpUserID(ctx)
groupMember.JoinSource = constant.JoinByInvitation
groupMember.InviterUserID = tracelog.GetOpUserID(ctx)
if err := CallbackBeforeMemberJoinGroup(ctx, tracelog.GetOperationID(ctx), groupMember, group.Ex); err != nil {
if err := CallbackBeforeMemberJoinGroup(ctx, groupMember, group.Ex); err != nil {
return err
}
groupMembers = append(groupMembers, groupMember)
@ -198,11 +265,11 @@ func (s *groupServer) CreateGroup(ctx context.Context, req *pbGroup.CreateGroupR
if req.GroupInfo.GroupType == constant.SuperGroup {
go func() {
for _, userID := range userIDs {
notification.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
chat.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
}
}()
} else {
notification.GroupCreatedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), group.GroupID, userIDs)
chat.GroupCreatedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), group.GroupID, userIDs)
}
return resp, nil
}
@ -240,7 +307,7 @@ func (s *groupServer) GetJoinedGroupList(ctx context.Context, req *pbGroup.GetJo
})
resp.Groups = utils.Slice(utils.Order(groupIDs, groups, func(group *relationTb.GroupModel) string {
return group.GroupID
}), func(group *relationTb.GroupModel) *open_im_sdk.GroupInfo {
}), func(group *relationTb.GroupModel) *sdkws.GroupInfo {
return DbToPbGroupInfo(group, ownerMap[group.GroupID].UserID, groupMemberNum[group.GroupID])
})
return resp, nil
@ -271,13 +338,10 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
if ids := utils.Single(req.InvitedUserIDs, utils.Keys(memberMap)); len(ids) > 0 {
return nil, constant.ErrArgs.Wrap("user in group " + strings.Join(ids, ","))
}
userMap, err := GetUserInfoMap(ctx, req.InvitedUserIDs)
userMap, err := s.user.GetUsersInfoMap(ctx, req.InvitedUserIDs, true)
if err != nil {
return nil, err
}
if ids := utils.Single(req.InvitedUserIDs, utils.Keys(userMap)); len(ids) > 0 {
return nil, constant.ErrArgs.Wrap("user not found " + strings.Join(ids, ","))
}
if group.NeedVerification == constant.AllNeedVerification {
if !tokenverify.IsAppManagerUid(ctx) {
opUserID := tracelog.GetOpUserID(ctx)
@ -299,7 +363,7 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
return nil, err
}
for _, request := range requests {
notification.JoinGroupApplicationNotification(ctx, &pbGroup.JoinGroupReq{
chat.JoinGroupApplicationNotification(ctx, &pbGroup.JoinGroupReq{
GroupID: request.GroupID,
ReqMessage: request.ReqMsg,
JoinSource: request.JoinSource,
@ -315,7 +379,7 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
return nil, err
}
for _, userID := range req.InvitedUserIDs {
notification.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
chat.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
}
} else {
opUserID := tracelog.GetOpUserID(ctx)
@ -328,7 +392,7 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
member.OperatorUserID = opUserID
member.InviterUserID = opUserID
member.JoinSource = constant.JoinByInvitation
if err := CallbackBeforeMemberJoinGroup(ctx, tracelog.GetOperationID(ctx), member, group.Ex); err != nil {
if err := CallbackBeforeMemberJoinGroup(ctx, member, group.Ex); err != nil {
return nil, err
}
groupMembers = append(groupMembers, member)
@ -336,7 +400,7 @@ func (s *groupServer) InviteUserToGroup(ctx context.Context, req *pbGroup.Invite
if err := s.GroupInterface.CreateGroup(ctx, nil, groupMembers); err != nil {
return nil, err
}
notification.MemberInvitedNotification(tracelog.GetOperationID(ctx), req.GroupID, tracelog.GetOpUserID(ctx), req.Reason, req.InvitedUserIDs)
chat.MemberInvitedNotification(tracelog.GetOperationID(ctx), req.GroupID, tracelog.GetOpUserID(ctx), req.Reason, req.InvitedUserIDs)
}
return resp, nil
}
@ -354,13 +418,13 @@ func (s *groupServer) GetGroupAllMember(ctx context.Context, req *pbGroup.GetGro
if err != nil {
return nil, err
}
nameMap, err := GetUsername(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
nameMap, err := s.GetUsernameMap(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
return e.UserID, e.Nickname == ""
}))
}), true)
if err != nil {
return nil, err
}
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *sdkws.GroupMemberFullInfo {
if e.Nickname == "" {
e.Nickname = nameMap[e.UserID]
}
@ -376,13 +440,13 @@ func (s *groupServer) GetGroupMemberList(ctx context.Context, req *pbGroup.GetGr
return nil, err
}
resp.Total = total
nameMap, err := GetUsername(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
nameMap, err := s.GetUsernameMap(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
return e.UserID, e.Nickname == ""
}))
}), true)
if err != nil {
return nil, err
}
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *sdkws.GroupMemberFullInfo {
if e.Nickname == "" {
e.Nickname = nameMap[e.UserID]
}
@ -413,7 +477,7 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
}
go func() {
for _, userID := range req.KickedUserIDs {
notification.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
chat.SuperGroupNotification(tracelog.GetOperationID(ctx), userID, userID)
}
}()
} else {
@ -453,7 +517,7 @@ func (s *groupServer) KickGroupMember(ctx context.Context, req *pbGroup.KickGrou
if err := s.GroupInterface.DeleteGroupMember(ctx, group.GroupID, req.KickedUserIDs); err != nil {
return nil, err
}
notification.MemberKickedNotification(req, req.KickedUserIDs)
chat.MemberKickedNotification(req, req.KickedUserIDs)
}
return resp, nil
}
@ -470,13 +534,13 @@ func (s *groupServer) GetGroupMembersInfo(ctx context.Context, req *pbGroup.GetG
if err != nil {
return nil, err
}
nameMap, err := GetUsername(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
nameMap, err := s.GetUsernameMap(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
return e.UserID, e.Nickname == ""
}))
}), true)
if err != nil {
return nil, err
}
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *sdkws.GroupMemberFullInfo {
if e.Nickname == "" {
e.Nickname = nameMap[e.UserID]
}
@ -505,13 +569,10 @@ func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.
}
userIDs = utils.Distinct(userIDs)
groupIDs = utils.Distinct(groupIDs)
userMap, err := GetPublicUserInfoMap(ctx, userIDs)
userMap, err := s.user.GetPublicUserInfoMap(ctx, userIDs, true)
if err != nil {
return nil, err
}
if ids := utils.Single(utils.Keys(userMap), userIDs); len(ids) > 0 {
return nil, constant.ErrUserIDNotFound.Wrap(strings.Join(ids, ","))
}
groups, err := s.GroupInterface.FindGroup(ctx, utils.Distinct(groupIDs))
if err != nil {
return nil, err
@ -533,7 +594,7 @@ func (s *groupServer) GetGroupApplicationList(ctx context.Context, req *pbGroup.
ownerMap := utils.SliceToMap(owners, func(e *relationTb.GroupMemberModel) string {
return e.GroupID
})
resp.GroupRequests = utils.Slice(groupRequests, func(e *relationTb.GroupRequestModel) *open_im_sdk.GroupRequest {
resp.GroupRequests = utils.Slice(groupRequests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest {
return DbToPbGroupRequest(e, userMap[e.UserID], DbToPbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, uint32(groupMemberNumMap[e.GroupID])))
})
return resp, nil
@ -559,7 +620,7 @@ func (s *groupServer) GetGroupsInfo(ctx context.Context, req *pbGroup.GetGroupsI
ownerMap := utils.SliceToMap(owners, func(e *relationTb.GroupMemberModel) string {
return e.GroupID
})
resp.GroupInfos = utils.Slice(groups, func(e *relationTb.GroupModel) *open_im_sdk.GroupInfo {
resp.GroupInfos = utils.Slice(groups, func(e *relationTb.GroupModel) *sdkws.GroupInfo {
return DbToPbGroupInfo(e, ownerMap[e.GroupID].UserID, uint32(groupMemberNumMap[e.GroupID]))
})
return resp, nil
@ -590,19 +651,18 @@ func (s *groupServer) GroupApplicationResponse(ctx context.Context, req *pbGroup
if groupRequest.HandleResult != 0 {
return nil, constant.ErrArgs.Wrap("group request already processed")
}
if _, err := s.GroupInterface.TakeGroupMember(ctx, req.GroupID, req.FromUserID); err != nil {
if !IsNotFound(err) {
return nil, err
}
} else {
return nil, constant.ErrArgs.Wrap("already in group")
var join bool
if _, err = s.GroupInterface.TakeGroupMember(ctx, req.GroupID, req.FromUserID); err == nil {
join = true // 已经在群里了
} else if !s.IsNotFound(err) {
return nil, err
}
user, err := GetPublicUserInfoOne(ctx, req.FromUserID)
user, err := s.user.GetPublicUserInfo(ctx, req.FromUserID)
if err != nil {
return nil, err
}
var member *relationTb.GroupMemberModel
if req.HandleResult == constant.GroupResponseAgree {
if (!join) && req.HandleResult == constant.GroupResponseAgree {
member = &relationTb.GroupMemberModel{
GroupID: req.GroupID,
UserID: user.UserID,
@ -615,25 +675,27 @@ func (s *groupServer) GroupApplicationResponse(ctx context.Context, req *pbGroup
OperatorUserID: tracelog.GetOpUserID(ctx),
Ex: groupRequest.Ex,
}
if err = CallbackBeforeMemberJoinGroup(ctx, tracelog.GetOperationID(ctx), member, group.Ex); err != nil {
if err = CallbackBeforeMemberJoinGroup(ctx, member, group.Ex); err != nil {
return nil, err
}
}
if err := s.GroupInterface.HandlerGroupRequest(ctx, req.GroupID, req.FromUserID, req.HandledMsg, req.HandleResult, member); err != nil {
return nil, err
}
if req.HandleResult == constant.GroupResponseAgree {
notification.GroupApplicationAcceptedNotification(req)
notification.MemberEnterNotification(req)
} else if req.HandleResult == constant.GroupResponseRefuse {
notification.GroupApplicationRejectedNotification(req)
if !join {
if req.HandleResult == constant.GroupResponseAgree {
chat.GroupApplicationAcceptedNotification(req)
chat.MemberEnterNotification(ctx, req)
} else if req.HandleResult == constant.GroupResponseRefuse {
chat.GroupApplicationRejectedNotification(req)
}
}
return resp, nil
}
func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq) (*pbGroup.JoinGroupResp, error) {
resp := &pbGroup.JoinGroupResp{}
if _, err := GetPublicUserInfoOne(ctx, tracelog.GetOpUserID(ctx)); err != nil {
if _, err := s.user.GetPublicUserInfo(ctx, tracelog.GetOpUserID(ctx)); err != nil {
return nil, err
}
group, err := s.GroupInterface.TakeGroup(ctx, req.GroupID)
@ -657,13 +719,13 @@ func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq)
groupMember.OperatorUserID = tracelog.GetOpUserID(ctx)
groupMember.JoinSource = constant.JoinByInvitation
groupMember.InviterUserID = tracelog.GetOpUserID(ctx)
if err := CallbackBeforeMemberJoinGroup(ctx, tracelog.GetOperationID(ctx), groupMember, group.Ex); err != nil {
if err := CallbackBeforeMemberJoinGroup(ctx, groupMember, group.Ex); err != nil {
return nil, err
}
if err := s.GroupInterface.CreateGroup(ctx, nil, []*relationTb.GroupMemberModel{groupMember}); err != nil {
return nil, err
}
notification.MemberEnterDirectlyNotification(req.GroupID, tracelog.GetOpUserID(ctx), tracelog.GetOperationID(ctx))
chat.MemberEnterDirectlyNotification(req.GroupID, tracelog.GetOpUserID(ctx), tracelog.GetOperationID(ctx))
return resp, nil
}
groupRequest := relationTb.GroupRequestModel{
@ -676,7 +738,7 @@ func (s *groupServer) JoinGroup(ctx context.Context, req *pbGroup.JoinGroupReq)
if err := s.GroupInterface.CreateGroupRequest(ctx, []*relationTb.GroupRequestModel{&groupRequest}); err != nil {
return nil, err
}
notification.JoinGroupApplicationNotification(ctx, req)
chat.JoinGroupApplicationNotification(ctx, req)
return resp, nil
}
@ -690,13 +752,13 @@ func (s *groupServer) QuitGroup(ctx context.Context, req *pbGroup.QuitGroupReq)
if err := s.GroupInterface.DeleteSuperGroupMember(ctx, req.GroupID, []string{tracelog.GetOpUserID(ctx)}); err != nil {
return nil, err
}
notification.SuperGroupNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), tracelog.GetOpUserID(ctx))
chat.SuperGroupNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), tracelog.GetOpUserID(ctx))
} else {
_, err := s.GroupInterface.TakeGroupMember(ctx, req.GroupID, tracelog.GetOpUserID(ctx))
if err != nil {
return nil, err
}
notification.MemberQuitNotification(req)
chat.MemberQuitNotification(req)
}
return resp, nil
}
@ -730,9 +792,9 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
if err != nil {
return nil, err
}
notification.GroupInfoSetNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupInfoForSet.GroupID, group.GroupName, group.Notification, group.Introduction, group.FaceURL, req.GroupInfoForSet.NeedVerification)
chat.GroupInfoSetNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupInfoForSet.GroupID, group.GroupName, group.Notification, group.Introduction, group.FaceURL, req.GroupInfoForSet.NeedVerification)
if req.GroupInfoForSet.Notification != "" {
GroupNotification(ctx, group.GroupID)
s.GroupNotification(ctx, group.GroupID)
}
return resp, nil
}
@ -780,7 +842,7 @@ func (s *groupServer) TransferGroupOwner(ctx context.Context, req *pbGroup.Trans
if err := s.GroupInterface.TransferGroupOwner(ctx, req.GroupID, req.OldOwnerUserID, req.NewOwnerUserID, newOwner.RoleLevel); err != nil {
return nil, err
}
notification.GroupOwnerTransferredNotification(req)
chat.GroupOwnerTransferredNotification(req)
return resp, nil
}
@ -830,13 +892,13 @@ func (s *groupServer) GetGroupMembersCMS(ctx context.Context, req *pbGroup.GetGr
return nil, err
}
resp.Total = total
nameMap, err := GetUsername(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
nameMap, err := s.GetUsernameMap(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
return e.UserID, e.Nickname == ""
}))
}), true)
if err != nil {
return nil, err
}
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *sdkws.GroupMemberFullInfo {
if e.Nickname == "" {
e.Nickname = nameMap[e.UserID]
}
@ -847,7 +909,7 @@ func (s *groupServer) GetGroupMembersCMS(ctx context.Context, req *pbGroup.GetGr
func (s *groupServer) GetUserReqApplicationList(ctx context.Context, req *pbGroup.GetUserReqApplicationListReq) (*pbGroup.GetUserReqApplicationListResp, error) {
resp := &pbGroup.GetUserReqApplicationListResp{}
user, err := GetPublicUserInfoOne(ctx, req.UserID)
user, err := s.user.GetPublicUserInfo(ctx, req.UserID)
if err != nil {
return nil, err
}
@ -886,7 +948,7 @@ func (s *groupServer) GetUserReqApplicationList(ctx context.Context, req *pbGrou
if err != nil {
return nil, err
}
resp.GroupRequests = utils.Slice(requests, func(e *relationTb.GroupRequestModel) *open_im_sdk.GroupRequest {
resp.GroupRequests = utils.Slice(requests, func(e *relationTb.GroupRequestModel) *sdkws.GroupRequest {
return DbToPbGroupRequest(e, user, DbToPbGroupInfo(groupMap[e.GroupID], ownerMap[e.GroupID].UserID, uint32(groupMemberNum[e.GroupID])))
})
return resp, nil
@ -912,7 +974,7 @@ func (s *groupServer) DismissGroup(ctx context.Context, req *pbGroup.DismissGrou
return nil, err
}
} else {
notification.GroupDismissedNotification(req)
chat.GroupDismissedNotification(req)
}
return resp, nil
}
@ -936,7 +998,7 @@ func (s *groupServer) MuteGroupMember(ctx context.Context, req *pbGroup.MuteGrou
if err := s.GroupInterface.UpdateGroupMember(ctx, member.GroupID, member.UserID, data); err != nil {
return nil, err
}
notification.GroupMemberMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID, req.UserID, req.MutedSeconds)
chat.GroupMemberMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID, req.UserID, req.MutedSeconds)
return resp, nil
}
@ -959,7 +1021,7 @@ func (s *groupServer) CancelMuteGroupMember(ctx context.Context, req *pbGroup.Ca
if err := s.GroupInterface.UpdateGroupMember(ctx, member.GroupID, member.UserID, data); err != nil {
return nil, err
}
notification.GroupMemberCancelMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID, req.UserID)
chat.GroupMemberCancelMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID, req.UserID)
return resp, nil
}
@ -971,7 +1033,7 @@ func (s *groupServer) MuteGroup(ctx context.Context, req *pbGroup.MuteGroupReq)
if err := s.GroupInterface.UpdateGroup(ctx, req.GroupID, UpdateGroupStatusMap(constant.GroupStatusMuted)); err != nil {
return nil, err
}
notification.GroupMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID)
chat.GroupMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID)
return resp, nil
}
@ -983,7 +1045,7 @@ func (s *groupServer) CancelMuteGroup(ctx context.Context, req *pbGroup.CancelMu
if err := s.GroupInterface.UpdateGroup(ctx, req.GroupID, UpdateGroupStatusMap(constant.GroupOk)); err != nil {
return nil, err
}
notification.GroupCancelMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID)
chat.GroupCancelMutedNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), req.GroupID)
return resp, nil
}
@ -1060,7 +1122,7 @@ func (s *groupServer) SetGroupMemberInfo(ctx context.Context, req *pbGroup.SetGr
return nil, err
}
for _, member := range req.Members {
notification.GroupMemberInfoSetNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), member.GroupID, member.UserID)
chat.GroupMemberInfoSetNotification(tracelog.GetOperationID(ctx), tracelog.GetOpUserID(ctx), member.GroupID, member.UserID)
}
return resp, nil
}
@ -1105,13 +1167,13 @@ func (s *groupServer) GetUserInGroupMembers(ctx context.Context, req *pbGroup.Ge
if err != nil {
return nil, err
}
nameMap, err := GetUsername(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
nameMap, err := s.GetUsernameMap(ctx, utils.Filter(members, func(e *relationTb.GroupMemberModel) (string, bool) {
return e.UserID, e.Nickname == ""
}))
}), true)
if err != nil {
return nil, err
}
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *open_im_sdk.GroupMemberFullInfo {
resp.Members = utils.Slice(members, func(e *relationTb.GroupMemberModel) *sdkws.GroupMemberFullInfo {
if e.Nickname == "" {
e.Nickname = nameMap[e.UserID]
}

View File

@ -1,13 +0,0 @@
package group
import (
"Open_IM/pkg/common/tracelog"
"gorm.io/gorm"
)
func IsNotFound(err error) bool {
if err == nil {
return false
}
return tracelog.Unwrap(err) == gorm.ErrRecordNotFound
}

View File

@ -7,15 +7,15 @@ import (
commonDB "Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
promePkg "Open_IM/pkg/common/prometheus"
)
func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *open_im_sdk.GetMaxAndMinSeqReq) (*open_im_sdk.GetMaxAndMinSeqResp, error) {
func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *sdkws.GetMaxAndMinSeqReq) (*sdkws.GetMaxAndMinSeqResp, error) {
log.NewInfo(in.OperationID, "rpc getMaxAndMinSeq is arriving", in.String())
resp := new(open_im_sdk.GetMaxAndMinSeqResp)
m := make(map[string]*open_im_sdk.MaxAndMinSeq)
resp := new(sdkws.GetMaxAndMinSeqResp)
m := make(map[string]*sdkws.MaxAndMinSeq)
var maxSeq, minSeq uint64
var err1, err2 error
maxSeq, err1 = commonDB.DB.GetUserMaxSeq(in.UserID)
@ -35,7 +35,7 @@ func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *open_im_sdk.GetMaxAnd
resp.MaxSeq = uint32(maxSeq)
resp.MinSeq = uint32(minSeq)
for _, groupID := range in.GroupIDList {
x := new(open_im_sdk.MaxAndMinSeq)
x := new(sdkws.MaxAndMinSeq)
maxSeq, _ := commonDB.DB.GetGroupMaxSeq(groupID)
minSeq, _ := commonDB.DB.GetGroupUserMinSeq(groupID, in.UserID)
x.MaxSeq = uint32(maxSeq)
@ -46,10 +46,10 @@ func (rpc *rpcChat) GetMaxAndMinSeq(_ context.Context, in *open_im_sdk.GetMaxAnd
return resp, nil
}
func (rpc *rpcChat) PullMessageBySeqList(_ context.Context, in *open_im_sdk.PullMessageBySeqListReq) (*open_im_sdk.PullMessageBySeqListResp, error) {
func (rpc *rpcChat) PullMessageBySeqList(_ context.Context, in *sdkws.PullMessageBySeqListReq) (*sdkws.PullMessageBySeqListResp, error) {
log.NewInfo(in.OperationID, "rpc PullMessageBySeqList is arriving", in.String())
resp := new(open_im_sdk.PullMessageBySeqListResp)
m := make(map[string]*open_im_sdk.MsgDataList)
resp := new(sdkws.PullMessageBySeqListResp)
m := make(map[string]*sdkws.MsgDataList)
redisMsgList, failedSeqList, err := commonDB.DB.GetMessageListBySeq(in.UserID, in.SeqList, in.OperationID)
if err != nil {
if err != go_redis.Nil {
@ -76,7 +76,7 @@ func (rpc *rpcChat) PullMessageBySeqList(_ context.Context, in *open_im_sdk.Pull
}
for k, v := range in.GroupSeqList {
x := new(open_im_sdk.MsgDataList)
x := new(sdkws.MsgDataList)
redisMsgList, failedSeqList, err := commonDB.DB.GetMessageListBySeq(k, v.SeqList, in.OperationID)
if err != nil {
if err != go_redis.Nil {
@ -108,7 +108,7 @@ func (rpc *rpcChat) PullMessageBySeqList(_ context.Context, in *open_im_sdk.Pull
return resp, nil
}
type MsgFormats []*open_im_sdk.MsgData
type MsgFormats []*sdkws.MsgData
// Implement the sort.Interface interface to get the number of elements method
func (s MsgFormats) Len() int {

View File

@ -750,7 +750,7 @@ func modifyMessageByUserMessageReceiveOptoptimization(userID, sourceID string, s
type NotificationMsg struct {
SendID string
RecvID string
Content []byte // open_im_sdk.TipsComm
Content []byte // sdkws.TipsComm
MsgFrom int32
ContentType int32
SessionType int32
@ -975,14 +975,6 @@ func Notification(n *NotificationMsg) {
reliabilityLevel = config.Config.Notification.GroupMemberInfoSet.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.GroupMemberInfoSet.Conversation.UnreadCount
case constant.WorkMomentNotification:
pushSwitch = config.Config.Notification.WorkMomentsNotification.OfflinePush.PushSwitch
title = config.Config.Notification.WorkMomentsNotification.OfflinePush.Title
desc = config.Config.Notification.WorkMomentsNotification.OfflinePush.Desc
ex = config.Config.Notification.WorkMomentsNotification.OfflinePush.Ext
reliabilityLevel = config.Config.Notification.WorkMomentsNotification.Conversation.ReliabilityLevel
unReadCount = config.Config.Notification.WorkMomentsNotification.Conversation.UnreadCount
case constant.ConversationPrivateChatNotification:
pushSwitch = config.Config.Notification.ConversationSetPrivate.OfflinePush.PushSwitch
title = config.Config.Notification.ConversationSetPrivate.OfflinePush.Title

View File

@ -1,52 +0,0 @@
package msg
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
"Open_IM/pkg/getcdv3"
pbChat "Open_IM/pkg/proto/msg"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"strings"
)
func TagSendMessage(operationID string, user *im_mysql_model.User, recvID, content string, senderPlatformID int32) {
log.NewInfo(operationID, utils.GetSelfFuncName(), "args: ", user.UserID, recvID, content)
var req pbChat.SendMsgReq
var msgData pbCommon.MsgData
msgData.SendID = user.UserID
msgData.RecvID = recvID
msgData.ContentType = constant.Custom
msgData.SessionType = constant.SingleChatType
msgData.MsgFrom = constant.UserMsgType
msgData.Content = []byte(content)
msgData.SenderFaceURL = user.FaceURL
msgData.SenderNickname = user.Nickname
msgData.Options = map[string]bool{}
msgData.Options[constant.IsSenderConversationUpdate] = false
msgData.Options[constant.IsSenderNotificationPush] = false
msgData.CreateTime = utils.GetCurrentTimestampByMill()
msgData.ClientMsgID = utils.GetMsgID(user.UserID)
msgData.SenderPlatformID = senderPlatformID
req.MsgData = &msgData
req.OperationID = operationID
etcdConn := rpc.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImMsgName, operationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
return
}
client := pbChat.NewMsgClient(etcdConn)
respPb, err := client.SendMsg(context.Background(), &req)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "send msg failed", err.Error())
return
}
if respPb.ErrCode != 0 {
log.NewError(operationID, utils.GetSelfFuncName(), "send tag msg failed ", respPb)
}
}

View File

@ -1,734 +0,0 @@
package office
import (
"Open_IM/internal/common/notification"
"Open_IM/internal/rpc/msg"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/db/mysql_model/im_mysql_model"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
rocksCache "Open_IM/pkg/common/db/rocks_cache"
"Open_IM/pkg/common/log"
promePkg "Open_IM/pkg/common/prometheus"
pbCache "Open_IM/pkg/proto/cache"
pbOffice "Open_IM/pkg/proto/office"
pbCommon "Open_IM/pkg/proto/sdkws"
"Open_IM/pkg/utils"
"context"
"github.com/OpenIMSDK/getcdv3"
"net"
"strconv"
"strings"
"sync"
"time"
"unsafe"
grpcPrometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"google.golang.org/grpc"
)
type officeServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
ch chan tagSendStruct
}
func NewOfficeServer(port int) *officeServer {
log.NewPrivateLog(constant.LogFileName)
ch := make(chan tagSendStruct, 100000)
return &officeServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImOfficeName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
ch: ch,
}
}
func (s *officeServer) Run() {
log.NewInfo("0", "officeServer rpc start ")
listenIP := ""
if config.Config.ListenIP == "" {
listenIP = "0.0.0.0"
} else {
listenIP = config.Config.ListenIP
}
address := listenIP + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", address)
if err != nil {
panic("listening err:" + err.Error() + s.rpcRegisterName)
}
log.NewInfo("0", "listen network success, ", address, listener)
defer listener.Close()
//grpc server
recvSize := 1024 * 1024 * 30
sendSize := 1024 * 1024 * 30
var grpcOpts = []grpc.ServerOption{
grpc.MaxRecvMsgSize(recvSize),
grpc.MaxSendMsgSize(sendSize),
}
if config.Config.Prometheus.Enable {
promePkg.NewGrpcRequestCounter()
promePkg.NewGrpcRequestFailedCounter()
promePkg.NewGrpcRequestSuccessCounter()
grpcOpts = append(grpcOpts, []grpc.ServerOption{
// grpc.UnaryInterceptor(promePkg.UnaryServerInterceptorProme),
grpc.StreamInterceptor(grpcPrometheus.StreamServerInterceptor),
grpc.UnaryInterceptor(grpcPrometheus.UnaryServerInterceptor),
}...)
}
srv := grpc.NewServer(grpcOpts...)
defer srv.GracefulStop()
//Service registers with etcd
pbOffice.RegisterOfficeServiceServer(srv, s)
rpcRegisterIP := config.Config.RpcRegisterIP
if config.Config.RpcRegisterIP == "" {
rpcRegisterIP, err = utils.GetLocalIP()
if err != nil {
log.Error("", "GetLocalIP failed ", err.Error())
}
}
log.NewInfo("", "rpcRegisterIP", rpcRegisterIP)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), rpcRegisterIP, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
panic(utils.Wrap(err, "register office module rpc to etcd err"))
}
go s.sendTagMsgRoutine()
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "message cms rpc success")
}
type tagSendStruct struct {
operationID string
user *imdb.User
userID string
content string
senderPlatformID int32
}
func (s *officeServer) sendTagMsgRoutine() {
log.NewInfo("", utils.GetSelfFuncName(), "start")
for {
select {
case v := <-s.ch:
msg.TagSendMessage(v.operationID, v.user, v.userID, v.content, v.senderPlatformID)
time.Sleep(time.Millisecond * 100)
}
}
}
func (s *officeServer) GetUserTags(_ context.Context, req *pbOffice.GetUserTagsReq) (resp *pbOffice.GetUserTagsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req ", req.String())
resp = &pbOffice.GetUserTagsResp{
CommonResp: &pbOffice.CommonResp{},
Tags: []*pbOffice.Tag{},
}
tags, err := db.DB.GetUserTags(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "tags: ", tags)
for _, v := range tags {
tag := &pbOffice.Tag{
TagID: v.TagID,
TagName: v.TagName,
}
for _, userID := range v.UserList {
UserName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue
}
tag.UserList = append(tag.UserList, &pbOffice.TagUser{
UserID: userID,
UserName: UserName,
})
}
resp.Tags = append(resp.Tags, tag)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp ", resp.String())
return resp, nil
}
func (s *officeServer) CreateTag(_ context.Context, req *pbOffice.CreateTagReq) (resp *pbOffice.CreateTagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "CreateTag req", req.String())
userIDList := utils.RemoveRepeatedStringInList(req.UserIDList)
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "userIDList: ", userIDList)
resp = &pbOffice.CreateTagResp{CommonResp: &pbOffice.CommonResp{}}
if err := db.DB.CreateTag(req.UserID, req.TagName, userIDList); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserTags failed", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp", resp.String())
return resp, nil
}
func (s *officeServer) DeleteTag(_ context.Context, req *pbOffice.DeleteTagReq) (resp *pbOffice.DeleteTagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.DeleteTagResp{CommonResp: &pbOffice.CommonResp{}}
if err := db.DB.DeleteTag(req.UserID, req.TagID); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteTag failed", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) SetTag(_ context.Context, req *pbOffice.SetTagReq) (resp *pbOffice.SetTagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SetTagResp{CommonResp: &pbOffice.CommonResp{}}
increaseUserIDList := utils.RemoveRepeatedStringInList(req.IncreaseUserIDList)
reduceUserIDList := utils.RemoveRepeatedStringInList(req.ReduceUserIDList)
if err := db.DB.SetTag(req.UserID, req.TagID, req.NewName, increaseUserIDList, reduceUserIDList); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetTag failed", increaseUserIDList, reduceUserIDList, err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) SendMsg2Tag(_ context.Context, req *pbOffice.SendMsg2TagReq) (resp *pbOffice.SendMsg2TagResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SendMsg2TagResp{CommonResp: &pbOffice.CommonResp{}}
var tagUserIDList []string
for _, tagID := range req.TagList {
userIDList, err := db.DB.GetUserIDListByTagID(req.SendID, tagID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserIDListByTagID failed", err.Error())
continue
}
tagUserIDList = append(tagUserIDList, userIDList...)
}
var groupUserIDList []string
for _, groupID := range req.GroupList {
etcdConn := getcdv3.GetDefaultConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImCacheName, req.OperationID)
if etcdConn == nil {
errMsg := req.OperationID + "getcdv3.GetDefaultConn == nil"
log.NewError(req.OperationID, errMsg)
resp.CommonResp.ErrCode = constant.ErrInternal.ErrCode
resp.CommonResp.ErrMsg = errMsg
return resp, nil
}
cacheClient := pbCache.NewCacheClient(etcdConn)
req := pbCache.GetGroupMemberIDListFromCacheReq{
OperationID: req.OperationID,
GroupID: groupID,
}
getGroupMemberIDListFromCacheResp, err := cacheClient.GetGroupMemberIDListFromCache(context.Background(), &req)
if err != nil {
log.NewError(req.OperationID, "GetGroupMemberIDListFromCache rpc call failed ", err.Error(), req.String())
resp.CommonResp.ErrCode = constant.ErrServer.ErrCode
resp.CommonResp.ErrMsg = err.Error()
return resp, nil
}
if getGroupMemberIDListFromCacheResp.CommonResp.ErrCode != 0 {
log.NewError(req.OperationID, "GetGroupMemberIDListFromCache rpc logic call failed ", getGroupMemberIDListFromCacheResp.CommonResp.ErrCode)
resp.CommonResp.ErrCode = getGroupMemberIDListFromCacheResp.CommonResp.ErrCode
resp.CommonResp.ErrMsg = getGroupMemberIDListFromCacheResp.CommonResp.ErrMsg
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), getGroupMemberIDListFromCacheResp.UserIDList)
groupUserIDList = append(groupUserIDList, getGroupMemberIDListFromCacheResp.UserIDList...)
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), groupUserIDList, req.GroupList)
var userIDList []string
userIDList = append(userIDList, tagUserIDList...)
userIDList = append(userIDList, groupUserIDList...)
userIDList = append(userIDList, req.UserList...)
userIDList = utils.RemoveRepeatedStringInList(userIDList)
for i, userID := range userIDList {
if userID == req.SendID || userID == "" {
userIDList = append(userIDList[:i], userIDList[i+1:]...)
}
}
if unsafe.Sizeof(userIDList) > 1024*1024 {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "size", unsafe.Sizeof(userIDList))
resp.CommonResp.ErrMsg = constant.ErrSendLimit.ErrMsg
resp.CommonResp.ErrCode = constant.ErrSendLimit.ErrCode
return
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "total userIDList result: ", userIDList)
user, err := imdb.GetUserByUserID(req.SendID)
if err != nil {
log.NewError(req.OperationID, "GetUserByUserID failed ", err.Error(), req.SendID)
resp.CommonResp.ErrMsg = err.Error()
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
var successUserIDList []string
for _, userID := range userIDList {
t := tagSendStruct{
operationID: req.OperationID,
user: user,
userID: userID,
content: req.Content,
senderPlatformID: req.SenderPlatformID,
}
select {
case s.ch <- t:
log.NewDebug(t.operationID, utils.GetSelfFuncName(), "msg: ", t, "send success")
successUserIDList = append(successUserIDList, userID)
// if channel is full, return grpc req
case <-time.After(1 * time.Second):
log.NewError(t.operationID, utils.GetSelfFuncName(), s.ch, "channel is full")
resp.CommonResp.ErrCode = constant.ErrSendLimit.ErrCode
resp.CommonResp.ErrMsg = constant.ErrSendLimit.ErrMsg
return resp, nil
}
}
var tagSendLogs mongoDB.TagSendLog
var wg sync.WaitGroup
wg.Add(len(successUserIDList))
var lock sync.Mutex
for _, userID := range successUserIDList {
go func(userID string) {
defer wg.Done()
userName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error(), userID)
return
}
lock.Lock()
tagSendLogs.UserList = append(tagSendLogs.UserList, mongoDB.TagUser{
UserID: userID,
UserName: userName,
})
lock.Unlock()
}(userID)
}
wg.Wait()
tagSendLogs.SendID = req.SendID
tagSendLogs.Content = req.Content
tagSendLogs.SenderPlatformID = req.SenderPlatformID
tagSendLogs.SendTime = time.Now().Unix()
if err := db.DB.SaveTagSendLog(&tagSendLogs); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SaveTagSendLog failed", tagSendLogs, err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetTagSendLogs(_ context.Context, req *pbOffice.GetTagSendLogsReq) (resp *pbOffice.GetTagSendLogsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetTagSendLogsResp{
CommonResp: &pbOffice.CommonResp{},
Pagination: &pbCommon.ResponsePagination{
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
},
TagSendLogs: []*pbOffice.TagSendLog{},
}
tagSendLogs, err := db.DB.GetTagSendLogs(req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTagSendLogs", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
if err := utils.CopyStructFields(&resp.TagSendLogs, tagSendLogs); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetUserTagByID(_ context.Context, req *pbOffice.GetUserTagByIDReq) (resp *pbOffice.GetUserTagByIDResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserTagByIDResp{
CommonResp: &pbOffice.CommonResp{},
Tag: &pbOffice.Tag{},
}
tag, err := db.DB.GetTagByID(req.UserID, req.TagID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTagByID failed", err.Error())
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
return resp, nil
}
for _, userID := range tag.UserList {
userName, err := im_mysql_model.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue
}
resp.Tag.UserList = append(resp.Tag.UserList, &pbOffice.TagUser{
UserID: userID,
UserName: userName,
})
}
resp.Tag.TagID = tag.TagID
resp.Tag.TagName = tag.TagName
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) CreateOneWorkMoment(_ context.Context, req *pbOffice.CreateOneWorkMomentReq) (resp *pbOffice.CreateOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.CreateOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
workMoment := mongoDB.WorkMoment{
Comments: []*mongoDB.Comment{},
LikeUserList: []*mongoDB.WorkMomentUser{},
PermissionUserList: []*mongoDB.WorkMomentUser{},
}
createUser, err := imdb.GetUserByUserID(req.WorkMoment.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserByUserID", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&workMoment, req.WorkMoment); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
workMoment.UserName = createUser.Nickname
workMoment.FaceURL = createUser.FaceURL
workMoment.PermissionUserIDList = s.getPermissionUserIDList(req.OperationID, req.WorkMoment.PermissionGroupList, req.WorkMoment.PermissionUserList)
workMoment.PermissionUserList = []*mongoDB.WorkMomentUser{}
for _, userID := range workMoment.PermissionUserIDList {
userName, err := imdb.GetUserNameByUserID(userID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
continue
}
workMoment.PermissionUserList = append(workMoment.PermissionUserList, &mongoDB.WorkMomentUser{
UserID: userID,
UserName: userName,
})
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "workMoment to create", workMoment)
err = db.DB.CreateOneWorkMoment(&workMoment)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CreateOneWorkMoment", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
// send notification to at users
for _, atUser := range req.WorkMoment.AtUserList {
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentAtUserNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: workMoment.UserID,
FaceURL: createUser.FaceURL,
UserName: createUser.Nickname,
CreateTime: workMoment.CreateTime,
}
notification.WorkMomentSendNotification(req.OperationID, atUser.UserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) DeleteComment(_ context.Context, req *pbOffice.DeleteCommentReq) (resp *pbOffice.DeleteCommentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.DeleteCommentResp{CommonResp: &pbOffice.CommonResp{}}
err = db.DB.DeleteComment(req.WorkMomentID, req.ContentID, req.OpUserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
resp.CommonResp.ErrMsg = constant.ErrDB.ErrMsg
resp.CommonResp.ErrCode = constant.ErrDB.ErrCode
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
// count and distinct permission users
func (s *officeServer) getPermissionUserIDList(operationID string, groupList []*pbOffice.PermissionGroup, userList []*pbOffice.WorkMomentUser) []string {
var permissionUserIDList []string
for _, group := range groupList {
groupMemberIDList, err := imdb.GetGroupMemberIDListByGroupID(group.GroupID)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "GetGroupMemberIDListByGroupID failed", group, err.Error())
continue
}
log.NewDebug(operationID, utils.GetSelfFuncName(), "groupMemberIDList: ", groupMemberIDList)
permissionUserIDList = append(permissionUserIDList, groupMemberIDList...)
}
var userIDList []string
for _, user := range userList {
userIDList = append(userIDList, user.UserID)
}
permissionUserIDList = append(permissionUserIDList, userIDList...)
permissionUserIDList = utils.RemoveRepeatedStringInList(permissionUserIDList)
return permissionUserIDList
}
func (s *officeServer) DeleteOneWorkMoment(_ context.Context, req *pbOffice.DeleteOneWorkMomentReq) (resp *pbOffice.DeleteOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.DeleteOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "workMoment", workMoment)
if workMoment.UserID != req.UserID {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "workMoment.UserID != req.WorkMomentID, delete failed", workMoment, req.WorkMomentID)
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrAccess.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}
return resp, nil
}
err = db.DB.DeleteOneWorkMoment(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteOneWorkMoment", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func isUserCanSeeWorkMoment(userID string, workMoment mongoDB.WorkMoment) bool {
if userID != workMoment.UserID {
switch workMoment.Permission {
case constant.WorkMomentPublic:
return true
case constant.WorkMomentPrivate:
return false
case constant.WorkMomentPermissionCanSee:
return utils.IsContain(userID, workMoment.PermissionUserIDList)
case constant.WorkMomentPermissionCantSee:
return !utils.IsContain(userID, workMoment.PermissionUserIDList)
}
return false
}
return true
}
func (s *officeServer) LikeOneWorkMoment(_ context.Context, req *pbOffice.LikeOneWorkMomentReq) (resp *pbOffice.LikeOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.LikeOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
user, err := imdb.GetUserByUserID(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMoment, like, err := db.DB.LikeOneWorkMoment(req.UserID, user.Nickname, req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "LikeOneWorkMoment failed ", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentLikeNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: user.UserID,
FaceURL: user.FaceURL,
UserName: user.Nickname,
CreateTime: int32(time.Now().Unix()),
}
// send notification
if like && workMoment.UserID != req.UserID {
notification.WorkMomentSendNotification(req.OperationID, workMoment.UserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) CommentOneWorkMoment(_ context.Context, req *pbOffice.CommentOneWorkMomentReq) (resp *pbOffice.CommentOneWorkMomentResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.CommentOneWorkMomentResp{CommonResp: &pbOffice.CommonResp{}}
commentUser, err := imdb.GetUserByUserID(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID commentUserName failed", req.UserID, err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
var replyUserName string
if req.ReplyUserID != "" {
replyUserName, err = imdb.GetUserNameByUserID(req.ReplyUserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserNameByUserID get replyUserName failed", req.ReplyUserID, err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
}
comment := &mongoDB.Comment{
UserID: req.UserID,
UserName: commentUser.Nickname,
ReplyUserID: req.ReplyUserID,
ReplyUserName: replyUserName,
Content: req.Content,
CreateTime: int32(time.Now().Unix()),
}
workMoment, err := db.DB.CommentOneWorkMoment(comment, req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CommentOneWorkMoment failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
workMomentNotificationMsg := &pbOffice.WorkMomentNotificationMsg{
NotificationMsgType: constant.WorkMomentCommentNotification,
WorkMomentID: workMoment.WorkMomentID,
WorkMomentContent: workMoment.Content,
UserID: commentUser.UserID,
FaceURL: commentUser.FaceURL,
UserName: commentUser.Nickname,
ReplyUserID: comment.ReplyUserID,
ReplyUserName: comment.ReplyUserName,
ContentID: comment.ContentID,
Content: comment.Content,
CreateTime: comment.CreateTime,
}
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "msg: ", *workMomentNotificationMsg)
if req.UserID != workMoment.UserID {
notification.WorkMomentSendNotification(req.OperationID, workMoment.UserID, workMomentNotificationMsg)
}
if req.ReplyUserID != "" && req.ReplyUserID != workMoment.UserID && req.ReplyUserID != req.UserID {
notification.WorkMomentSendNotification(req.OperationID, req.ReplyUserID, workMomentNotificationMsg)
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetWorkMomentByID(_ context.Context, req *pbOffice.GetWorkMomentByIDReq) (resp *pbOffice.GetWorkMomentByIDResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetWorkMomentByIDResp{
WorkMoment: &pbOffice.WorkMoment{},
CommonResp: &pbOffice.CommonResp{},
}
workMoment, err := db.DB.GetWorkMomentByID(req.WorkMomentID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetWorkMomentByID failed", err.Error())
return resp, nil
}
canSee := isUserCanSeeWorkMoment(req.OpUserID, *workMoment)
log.Debug(req.OperationID, utils.GetSelfFuncName(), canSee, req.OpUserID, *workMoment)
if !canSee {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "workMoments not access to user", canSee, workMoment, req.OpUserID)
}
if err := utils.CopyStructFields(resp.WorkMoment, workMoment); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields", err.Error())
}
user, err := imdb.GetUserByUserID(workMoment.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserByUserID failed", err.Error())
}
if user != nil {
resp.WorkMoment.FaceURL = user.FaceURL
resp.WorkMoment.UserName = user.Nickname
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetUserWorkMoments(_ context.Context, req *pbOffice.GetUserWorkMomentsReq) (resp *pbOffice.GetUserWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
var workMoments []mongoDB.WorkMoment
if req.UserID == req.OpUserID {
workMoments, err = db.DB.GetUserSelfWorkMoments(req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber)
} else {
friendIDList, err := rocksCache.GetFriendIDListFromCache(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: err.Error()}
return resp, nil
}
workMoments, err = db.DB.GetUserWorkMoments(req.OpUserID, req.UserID, req.Pagination.ShowNumber, req.Pagination.PageNumber, friendIDList)
}
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserWorkMoments failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
for _, v := range resp.WorkMoments {
user, err := imdb.GetUserByUserID(v.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
if user != nil {
v.UserName = user.Nickname
v.FaceURL = user.FaceURL
}
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) GetUserFriendWorkMoments(_ context.Context, req *pbOffice.GetUserFriendWorkMomentsReq) (resp *pbOffice.GetUserFriendWorkMomentsResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.GetUserFriendWorkMomentsResp{CommonResp: &pbOffice.CommonResp{}, WorkMoments: []*pbOffice.WorkMoment{}}
resp.Pagination = &pbCommon.ResponsePagination{CurrentPage: req.Pagination.PageNumber, ShowNumber: req.Pagination.ShowNumber}
var friendIDList []string
if config.Config.WorkMoment.OnlyFriendCanSee {
friendIDList, err = rocksCache.GetFriendIDListFromCache(req.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: err.Error()}
return resp, nil
}
}
workMoments, err := db.DB.GetUserFriendWorkMoments(req.Pagination.ShowNumber, req.Pagination.PageNumber, req.UserID, friendIDList)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserFriendWorkMoments", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
if err := utils.CopyStructFields(&resp.WorkMoments, workMoments); err != nil {
log.NewDebug(req.OperationID, utils.GetSelfFuncName(), "CopyStructFields failed", err.Error())
}
for _, v := range resp.WorkMoments {
user, err := rocksCache.GetUserInfoFromCache(v.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
if user != nil {
v.UserName = user.Nickname
v.FaceURL = user.FaceURL
}
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) SetUserWorkMomentsLevel(_ context.Context, req *pbOffice.SetUserWorkMomentsLevelReq) (resp *pbOffice.SetUserWorkMomentsLevelResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.SetUserWorkMomentsLevelResp{CommonResp: &pbOffice.CommonResp{}}
if err := db.DB.SetUserWorkMomentsLevel(req.UserID, req.Level); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "SetUserWorkMomentsLevel failed", err.Error())
resp.CommonResp = &pbOffice.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}
return resp, nil
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}
func (s *officeServer) ChangeWorkMomentPermission(_ context.Context, req *pbOffice.ChangeWorkMomentPermissionReq) (resp *pbOffice.ChangeWorkMomentPermissionResp, err error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp = &pbOffice.ChangeWorkMomentPermissionResp{CommonResp: &pbOffice.CommonResp{}}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp: ", resp.String())
return resp, nil
}

View File

@ -57,7 +57,7 @@ package apistruct
//}
//type GetBlackListResp struct {
// CommResp
// BlackUserInfoList []*open_im_sdk.PublicUserInfo `json:"-"`
// BlackUserInfoList []*sdkws.PublicUserInfo `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}
//
@ -99,7 +99,7 @@ package apistruct
//}
//type GetFriendsInfoResp struct {
// CommResp
// FriendInfoList []*open_im_sdk.FriendInfo `json:"-"`
// FriendInfoList []*sdkws.FriendInfo `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}
//
@ -109,7 +109,7 @@ package apistruct
//}
//type GetFriendListResp struct {
// CommResp
// FriendInfoList []*open_im_sdk.FriendInfo `json:"-"`
// FriendInfoList []*sdkws.FriendInfo `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}
//
@ -119,7 +119,7 @@ package apistruct
//}
//type GetFriendApplyListResp struct {
// CommResp
// FriendRequestList []*open_im_sdk.FriendRequest `json:"-"`
// FriendRequestList []*sdkws.FriendRequest `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}
//
@ -129,7 +129,7 @@ package apistruct
//}
//type GetSelfApplyListResp struct {
// CommResp
// FriendRequestList []*open_im_sdk.FriendRequest `json:"-"`
// FriendRequestList []*sdkws.FriendRequest `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}

View File

@ -1,7 +1,7 @@
package apistruct
import (
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
)
type CommResp struct {
@ -32,8 +32,8 @@ type GetGroupMembersInfoReq struct {
}
type GetGroupMembersInfoResp struct {
CommResp
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
MemberList []*sdkws.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
type InviteUserToGroupReq struct {
@ -53,7 +53,7 @@ type GetJoinedGroupListReq struct {
}
type GetJoinedGroupListResp struct {
CommResp
GroupInfoList []*open_im_sdk.GroupInfo `json:"-"`
GroupInfoList []*sdkws.GroupInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
@ -65,9 +65,9 @@ type GetGroupMemberListReq struct {
}
type GetGroupMemberListResp struct {
CommResp
NextSeq int32 `json:"nextSeq"`
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
NextSeq int32 `json:"nextSeq"`
MemberList []*sdkws.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
type GetGroupAllMemberReq struct {
@ -78,8 +78,8 @@ type GetGroupAllMemberReq struct {
}
type GetGroupAllMemberResp struct {
CommResp
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
MemberList []*sdkws.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
//
@ -91,7 +91,7 @@ type GetGroupAllMemberResp struct {
//}
//type GetGroupAllMemberListBySplitResp struct {
// CommResp
// MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
// MemberList []*sdkws.GroupMemberFullInfo `json:"-"`
// Map []map[string]interface{} `json:"data" swaggerignore:"true"`
//}
@ -109,7 +109,7 @@ type CreateGroupReq struct {
}
type CreateGroupResp struct {
CommResp
GroupInfo open_im_sdk.GroupInfo `json:"-"`
GroupInfo sdkws.GroupInfo `json:"-"`
Data map[string]interface{} `json:"data" swaggerignore:"true"`
}
@ -119,8 +119,8 @@ type GetGroupApplicationListReq struct {
}
type GetGroupApplicationListResp struct {
CommResp
GroupRequestList []*open_im_sdk.GroupRequest `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
GroupRequestList []*sdkws.GroupRequest `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
type GetUserReqGroupApplicationListReq struct {
@ -129,7 +129,7 @@ type GetUserReqGroupApplicationListReq struct {
}
type GetUserRespGroupApplicationResp struct {
GroupRequestList []*open_im_sdk.GroupRequest `json:"data"`
GroupRequestList []*sdkws.GroupRequest `json:"data"`
}
type GetGroupInfoReq struct {
@ -138,12 +138,12 @@ type GetGroupInfoReq struct {
}
type GetGroupInfoResp struct {
CommResp
GroupInfoList []*open_im_sdk.GroupInfo `json:"-"`
GroupInfoList []*sdkws.GroupInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
//type GroupInfoAlias struct {
// open_im_sdk.GroupInfo
// sdkws.GroupInfo
// NeedVerification int32 `protobuf:"bytes,13,opt,name=needVerification" json:"needVerification,omitempty"`
//}

View File

@ -1,88 +0,0 @@
package apistruct
import (
pbOffice "Open_IM/pkg/proto/office"
)
type GetUserTagsReq struct {
OperationID string `json:"operationID" binding:"required"`
}
type GetUserTagsResp struct {
CommResp
Data struct {
Tags []*pbOffice.Tag `json:"tags"`
} `json:"data"`
}
type CreateTagReq struct {
TagName string `json:"tagName" binding:"required"` // tag名称
UserIDList []string `json:"userIDList" binding:"required"` // 用户ID列表
OperationID string `json:"operationID" binding:"required"`
}
type CreateTagResp struct {
CommResp
}
type DeleteTagReq struct {
TagID string `json:"tagID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteTagResp struct {
CommResp
}
type SetTagReq struct {
TagID string `json:"tagID" binding:"required"`
NewName string `json:"newName"`
IncreaseUserIDList []string `json:"increaseUserIDList"`
ReduceUserIDList []string `json:"reduceUserIDList"`
OperationID string `json:"operationID" binding:"required"`
}
type SetTagResp struct {
CommResp
}
type SendMsg2TagReq struct {
TagList []string `json:"tagList"`
UserList []string `json:"userList"`
GroupList []string `json:"groupList"`
SenderPlatformID int32 `json:"senderPlatformID" binding:"required"`
Content string `json:"content" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type SendMsg2TagResp struct {
CommResp
}
type GetTagSendLogsReq struct {
PageNumber int32 `json:"pageNumber" binding:"required"`
ShowNumber int32 `json:"showNumber" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetTagSendLogsResp struct {
CommResp
Data struct {
Logs []*pbOffice.TagSendLog `json:"logs"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserTagByIDReq struct {
TagID string `json:"tagID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetUserTagByIDResp struct {
CommResp
Data struct {
Tag *pbOffice.Tag `json:"tag"`
} `json:"data"`
}

View File

@ -1,7 +1,7 @@
package apistruct
import (
open_im_sdk "Open_IM/pkg/proto/sdkws"
sdkws "Open_IM/pkg/proto/sdkws"
)
type GetUsersInfoReq struct {
@ -10,8 +10,8 @@ type GetUsersInfoReq struct {
}
type GetUsersInfoResp struct {
CommResp
UserInfoList []*open_im_sdk.PublicUserInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
UserInfoList []*sdkws.PublicUserInfo `json:"-"`
Data []map[string]interface{} `json:"data" swaggerignore:"true"`
}
type UpdateSelfUserInfoReq struct {
@ -35,7 +35,7 @@ type GetSelfUserInfoReq struct {
}
type GetSelfUserInfoResp struct {
CommResp
UserInfo *open_im_sdk.UserInfo `json:"-"`
UserInfo *sdkws.UserInfo `json:"-"`
Data map[string]interface{} `json:"data" swaggerignore:"true"`
}

View File

@ -1,138 +0,0 @@
package apistruct
import "Open_IM/pkg/proto/office"
type CreateOneWorkMomentReq struct {
office.CreateOneWorkMomentReq
}
type CreateOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type DeleteOneWorkMomentReq struct {
WorkMomentID string `json:"workMomentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type LikeOneWorkMomentReq struct {
WorkMomentID string `json:"workMomentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type LikeOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type CommentOneWorkMomentReq struct {
WorkMomentID string `json:"workMomentID" binding:"required"`
ReplyUserID string `json:"replyUserID"`
Content string `json:"content" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type CommentOneWorkMomentResp struct {
CommResp
Data struct{} `json:"data"`
}
type DeleteCommentReq struct {
WorkMomentID string `json:"workMomentID" binding:"required"`
ContentID string `json:"contentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteCommentResp struct {
CommResp
Data struct{} `json:"data"`
}
type WorkMomentsUserCommonReq struct {
PageNumber int32 `json:"pageNumber" binding:"required"`
ShowNumber int32 `json:"showNumber" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetWorkMomentByIDReq struct {
WorkMomentID string `json:"workMomentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type WorkMoment struct {
WorkMomentID string `json:"workMomentID"`
UserID string `json:"userID"`
Content string `json:"content"`
LikeUserList []*WorkMomentUser `json:"likeUsers"`
Comments []*Comment `json:"comments"`
FaceURL string `json:"faceURL"`
UserName string `json:"userName"`
AtUserList []*WorkMomentUser `json:"atUsers"`
PermissionUserList []*WorkMomentUser `json:"permissionUsers"`
CreateTime int32 `json:"createTime"`
Permission int32 `json:"permission"`
}
type WorkMomentUser struct {
UserID string `json:"userID"`
UserName string `json:"userName"`
}
type Comment struct {
UserID string `json:"userID"`
UserName string `json:"userName"`
ReplyUserID string `json:"replyUserID"`
ReplyUserName string `json:"replyUserName"`
ContentID string `json:"contentID"`
Content string `json:"content"`
CreateTime int32 `json:"createTime"`
}
type GetWorkMomentByIDResp struct {
CommResp
Data struct {
WorkMoment *WorkMoment `json:"workMoment"`
} `json:"data"`
}
type GetUserWorkMomentsReq struct {
WorkMomentsUserCommonReq
UserID string `json:"userID"`
}
type GetUserWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserFriendWorkMomentsReq struct {
WorkMomentsUserCommonReq
}
type GetUserFriendWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type SetUserWorkMomentsLevelReq struct {
office.SetUserWorkMomentsLevelReq
}
type SetUserWorkMomentsLevelResp struct {
CommResp
Data struct{} `json:"data"`
}

View File

@ -1,7 +1,7 @@
package callbackstruct
import (
"Open_IM/pkg/proto/group"
"Open_IM/pkg/apistruct"
common "Open_IM/pkg/proto/sdkws"
)
@ -9,7 +9,7 @@ type CallbackBeforeCreateGroupReq struct {
CallbackCommand string `json:"callbackCommand"`
OperationID string `json:"operationID"`
common.GroupInfo
InitMemberList []*group.GroupAddMemberInfo `json:"initMemberList"`
InitMemberList []*apistruct.GroupAddMemberInfo `json:"initMemberList"`
}
type CallbackBeforeCreateGroupResp struct {

View File

@ -1,56 +0,0 @@
package cmsstruct
import (
"Open_IM/pkg/api_struct"
sdkws "Open_IM/pkg/proto/sdkws"
)
type AdminLoginRequest struct {
AdminName string `json:"adminID" binding:"required"`
Secret string `json:"secret" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type AdminLoginResponse struct {
Token string `json:"token"`
UserName string `json:"userName"`
FaceURL string `json:"faceURL"`
}
type GetUserTokenRequest struct {
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
PlatFormID int32 `json:"platformID" binding:"required"`
}
type GetUserTokenResponse struct {
Token string `json:"token"`
ExpTime int64 `json:"expTime"`
}
type AddUserRegisterAddFriendIDListRequest struct {
OperationID string `json:"operationID" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
}
type AddUserRegisterAddFriendIDListResponse struct {
}
type ReduceUserRegisterAddFriendIDListRequest struct {
OperationID string `json:"operationID" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
Operation int32 `json:"operation"`
}
type ReduceUserRegisterAddFriendIDListResponse struct {
}
type GetUserRegisterAddFriendIDListRequest struct {
OperationID string `json:"operationID" binding:"required"`
apistruct.RequestPagination
}
type GetUserRegisterAddFriendIDListResponse struct {
Users []*sdkws.UserInfo `json:"users"`
apistruct.ResponsePagination
}

View File

@ -1,11 +0,0 @@
package cmsstruct
type RequestPagination struct {
PageNumber int `json:"pageNumber" binding:"required"`
ShowNumber int `json:"showNumber" binding:"required"`
}
type ResponsePagination struct {
CurrentPage int `json:"currentPage"`
ShowNumber int `json:"showNumber"`
}

View File

@ -1,25 +0,0 @@
package cmsstruct
type GetFriendsReq struct {
OperationID string `json:"operationID"`
UserID string `json:"userID"`
FriendUserName string `json:"friendUserName"`
FriendUserID string `json:"friendUserID"`
RequestPagination
}
type FriendInfo struct {
OwnerUserID string `json:"ownerUserID"`
Remark string `json:"remark"`
CreateTime uint32 `json:"createTime"`
UserID string `json:"userID"`
Nickname string `json:"nickName"`
AddSource int32 `json:"addSource"`
OperatorUserID string `json:"operatorUserID"`
}
type GetFriendsResp struct {
ResponsePagination
FriendInfoList []*FriendInfo `json:"friendInfoList"`
FriendNums int32 `json:"friendNums"`
}

View File

@ -1,64 +0,0 @@
package cmsstruct
type GroupResponse struct {
GroupOwnerName string `json:"GroupOwnerName"`
GroupOwnerID string `json:"GroupOwnerID"`
GroupID string `json:"groupID"`
GroupName string `json:"groupName"`
Notification string `json:"notification"`
Introduction string `json:"introduction"`
FaceURL string `json:"faceURL"`
OwnerUserID string `json:"ownerUserID"`
CreateTime uint32 `json:"createTime"`
MemberCount uint32 `json:"memberCount"`
Ex string `json:"ex"`
Status int32 `json:"status"`
CreatorUserID string `json:"creatorUserID"`
GroupType int32 `json:"groupType"`
NeedVerification int32 `json:"needVerification"`
LookMemberInfo int32 `json:"lookMemberInfo"`
ApplyMemberFriend int32 `json:"applyMemberFriend"`
NotificationUpdateTime uint32 `json:"notificationUpdateTime"`
NotificationUserID string `json:"notificationUserID"`
}
type GetGroupsRequest struct {
RequestPagination
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID"`
GroupName string `json:"groupName"`
}
type GetGroupsResponse struct {
Groups []GroupResponse `json:"groups"`
GroupNums int `json:"groupNums"`
ResponsePagination
}
type GetGroupMembersRequest struct {
GroupID string `form:"groupID" binding:"required"`
UserName string `form:"userName"`
OperationID string `json:"operationID" binding:"required"`
RequestPagination
}
type GroupMemberResponse struct {
GroupID string `json:"groupID"`
UserID string `json:"userID"`
RoleLevel int32 `json:"roleLevel"`
JoinTime int32 `json:"joinTime"`
Nickname string `json:"nickname"`
FaceURL string `json:"faceURL"`
AppMangerLevel int32 `json:"appMangerLevel"` //if >0
JoinSource int32 `json:"joinSource"`
OperatorUserID string `json:"operatorUserID"`
Ex string `json:"ex"`
MuteEndTime uint32 `json:"muteEndTime"`
InviterUserID string `json:"inviterUserID"`
}
type GetGroupMembersResponse struct {
GroupMembers []GroupMemberResponse `json:"groupMembers"`
ResponsePagination
MemberNums int `json:"memberNums"`
}

View File

@ -1,48 +0,0 @@
package cmsstruct
import (
pbCommon "Open_IM/pkg/proto/sdkws"
)
type GetChatLogsReq struct {
SessionType int `json:"sessionType"`
ContentType int `json:"contentType"`
Content string `json:"content"`
SendID string `json:"sendID"`
RecvID string `json:"recvID"`
GroupID string `json:"groupID"`
SendTime string `json:"sendTime"`
RequestPagination
OperationID string `json:"operationID"`
}
type ChatLog struct {
SendID string `json:"sendID,omitempty"`
RecvID string `json:"recvID,omitempty"`
GroupID string `json:"groupID,omitempty"`
ClientMsgID string `json:"clientMsgID,omitempty"`
ServerMsgID string `json:"serverMsgID,omitempty"`
SenderPlatformID int32 `json:"senderPlatformID,omitempty"`
SenderNickname string `json:"senderNickname,omitempty"`
SenderFaceURL string `json:"senderFaceURL,omitempty"`
SessionType int32 `json:"sessionType,omitempty"`
MsgFrom int32 `json:"msgFrom,omitempty"`
ContentType int32 `json:"contentType,omitempty"`
Content string `json:"content,omitempty"`
Seq uint32 `json:"seq,omitempty"`
SendTime int64 `json:"sendTime,omitempty"`
CreateTime int64 `json:"createTime,omitempty"`
Status int32 `json:"status,omitempty"`
Options map[string]bool `json:"options,omitempty"`
OfflinePushInfo *pbCommon.OfflinePushInfo `json:"offlinePushInfo,omitempty"`
AtUserIDList []string `json:"atUserIDList,omitempty"`
MsgDataList []byte `json:"msgDataList,omitempty"`
AttachedInfo string `json:"attachedInfo,omitempty"`
Ex string `json:"ex,omitempty"`
}
type GetChatLogsResp struct {
ChatLogs []*ChatLog `json:"chatLogs"`
ChatLogsNum int `json:"logNums"`
ResponsePagination
}

View File

@ -1,90 +0,0 @@
package cmsstruct
type GetStatisticsRequest struct {
From string `json:"from" binding:"required"`
To string `json:"to" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetMessageStatisticsRequest struct {
GetStatisticsRequest
}
type GetMessageStatisticsResponse struct {
PrivateMessageNum int `json:"privateMessageNum"`
GroupMessageNum int `json:"groupMessageNum"`
PrivateMessageNumList []struct {
Date string `json:"date"`
MessageNum int `json:"messageNum"`
} `json:"privateMessageNumList"`
GroupMessageNumList []struct {
Date string `json:"date"`
MessageNum int `json:"messageNum"`
} `json:"groupMessageNumList"`
}
type GetUserStatisticsRequest struct {
GetStatisticsRequest
}
type GetUserStatisticsResponse struct {
IncreaseUserNum int `json:"increaseUserNum"`
ActiveUserNum int `json:"activeUserNum"`
TotalUserNum int `json:"totalUserNum"`
IncreaseUserNumList []struct {
Date string `json:"date"`
IncreaseUserNum int `json:"increaseUserNum"`
} `json:"increaseUserNumList"`
ActiveUserNumList []struct {
Date string `json:"date"`
ActiveUserNum int `json:"activeUserNum"`
} `json:"activeUserNumList"`
TotalUserNumList []struct {
Date string `json:"date"`
TotalUserNum int `json:"totalUserNum"`
} `json:"totalUserNumList"`
}
type GetGroupStatisticsRequest struct {
GetStatisticsRequest
}
// 群聊统计
type GetGroupStatisticsResponse struct {
IncreaseGroupNum int `json:"increaseGroupNum"`
TotalGroupNum int `json:"totalGroupNum"`
IncreaseGroupNumList []struct {
Date string `json:"date"`
IncreaseGroupNum int `json:"increaseGroupNum"`
} `json:"increaseGroupNumList"`
TotalGroupNumList []struct {
Date string `json:"date"`
TotalGroupNum int `json:"totalGroupNum"`
} `json:"totalGroupNumList"`
}
type GetActiveUserRequest struct {
GetStatisticsRequest
// RequestPagination
}
type GetActiveUserResponse struct {
ActiveUserList []struct {
NickName string `json:"nickName"`
UserId string `json:"userID"`
MessageNum int `json:"messageNum"`
} `json:"activeUserList"`
}
type GetActiveGroupRequest struct {
GetStatisticsRequest
// RequestPagination
}
type GetActiveGroupResponse struct {
ActiveGroupList []struct {
GroupName string `json:"groupName"`
GroupId string `json:"groupID"`
MessageNum int `json:"messageNum"`
} `json:"activeGroupList"`
}

View File

@ -1,76 +0,0 @@
package cmsstruct
type UserResponse struct {
FaceURL string `json:"faceURL"`
Nickname string `json:"nickName"`
UserID string `json:"userID"`
CreateTime string `json:"createTime,omitempty"`
CreateIp string `json:"createIp,omitempty"`
LastLoginTime string `json:"lastLoginTime,omitempty"`
LastLoginIp string `json:"lastLoginIP,omitempty"`
LoginTimes int32 `json:"loginTimes"`
LoginLimit int32 `json:"loginLimit"`
IsBlock bool `json:"isBlock"`
PhoneNumber string `json:"phoneNumber"`
Email string `json:"email"`
Birth string `json:"birth"`
Gender int `json:"gender"`
}
type AddUserRequest struct {
OperationID string `json:"operationID" binding:"required"`
PhoneNumber string `json:"phoneNumber" binding:"required"`
UserId string `json:"userID" binding:"required"`
Name string `json:"name" binding:"required"`
Email string `json:"email"`
Birth string `json:"birth"`
Gender string `json:"gender"`
FaceURL string `json:"faceURL"`
}
type AddUserResponse struct {
}
type BlockUser struct {
UserResponse
BeginDisableTime string `json:"beginDisableTime"`
EndDisableTime string `json:"endDisableTime"`
}
type BlockUserRequest struct {
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
EndDisableTime string `json:"endDisableTime" binding:"required"`
}
type BlockUserResponse struct {
}
type UnblockUserRequest struct {
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type UnBlockUserResponse struct {
}
type GetBlockUsersRequest struct {
OperationID string `json:"operationID" binding:"required"`
RequestPagination
}
type GetBlockUsersResponse struct {
BlockUsers []BlockUser `json:"blockUsers"`
ResponsePagination
UserNums int32 `json:"userNums"`
}
type GetUserIDByEmailAndPhoneNumberRequest struct {
OperationID string `json:"operationID" binding:"required"`
PhoneNumber string `json:"phoneNumber"`
Email string `json:"email"`
}
type GetUserIDByEmailAndPhoneNumberResponse struct {
UserIDList []string `json:"userIDList"`
}

View File

@ -37,10 +37,6 @@ type config struct {
GinPort []int `yaml:"openImApiPort"`
ListenIP string `yaml:"listenIP"`
}
CmsApi struct {
GinPort []int `yaml:"openImCmsApiPort"`
ListenIP string `yaml:"listenIP"`
}
Sdk struct {
WsPort []int `yaml:"openImSdkWsPort"`
DataDir []string `yaml:"dataDir"`
@ -131,8 +127,6 @@ type config struct {
OpenImGroupPort []int `yaml:"openImGroupPort"`
OpenImAuthPort []int `yaml:"openImAuthPort"`
OpenImPushPort []int `yaml:"openImPushPort"`
OpenImAdminCmsPort []int `yaml:"openImAdminCmsPort"`
OpenImOfficePort []int `yaml:"openImOfficePort"`
OpenImConversationPort []int `yaml:"openImConversationPort"`
OpenImCachePort []int `yaml:"openImCachePort"`
OpenImRealTimeCommPort []int `yaml:"openImRealTimeCommPort"`
@ -146,8 +140,6 @@ type config struct {
OpenImRelayName string `yaml:"openImRelayName"`
OpenImGroupName string `yaml:"openImGroupName"`
OpenImAuthName string `yaml:"openImAuthName"`
OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
OpenImOfficeName string `yaml:"openImOfficeName"`
OpenImConversationName string `yaml:"openImConversationName"`
OpenImCacheName string `yaml:"openImCacheName"`
OpenImRealTimeCommName string `yaml:"openImRealTimeCommName"`
@ -473,16 +465,6 @@ type config struct {
CloseTips string `yaml:"closeTips"`
} `yaml:"defaultTips"`
} `yaml:"conversationSetPrivate"`
WorkMomentsNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"workMomentsNotification"`
JoinDepartmentNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"joinDepartmentNotification"`
Signal struct {
OfflinePush struct {
Title string `yaml:"title"`
@ -490,9 +472,6 @@ type config struct {
} `yaml:"signal"`
}
WorkMoment struct {
OnlyFriendCanSee bool `yaml:"onlyFriendCanSee"`
} `yaml:"workMoment"`
Rtc struct {
SignalTimeout string `yaml:"signalTimeout"`
} `yaml:"rtc"`
@ -506,11 +485,7 @@ type config struct {
GroupPrometheusPort []int `yaml:"groupPrometheusPort"`
AuthPrometheusPort []int `yaml:"authPrometheusPort"`
PushPrometheusPort []int `yaml:"pushPrometheusPort"`
AdminCmsPrometheusPort []int `yaml:"adminCmsPrometheusPort"`
OfficePrometheusPort []int `yaml:"officePrometheusPort"`
OrganizationPrometheusPort []int `yaml:"organizationPrometheusPort"`
ConversationPrometheusPort []int `yaml:"conversationPrometheusPort"`
CachePrometheusPort []int `yaml:"cachePrometheusPort"`
RealTimeCommPrometheusPort []int `yaml:"realTimeCommPrometheusPort"`
MessageTransferPrometheusPort []int `yaml:"messageTransferPrometheusPort"`
} `yaml:"prometheus"`

View File

@ -94,9 +94,6 @@ const (
ConversationPrivateChatNotification = 1701
ConversationUnreadNotification = 1702
WorkMomentNotificationBegin = 1900
WorkMomentNotification = 1901
BusinessNotificationBegin = 2000
BusinessNotification = 2001
BusinessNotificationEnd = 2099
@ -218,17 +215,6 @@ const (
VideoType = 2
ImageType = 3
// workMoment permission
WorkMomentPublic = 0
WorkMomentPrivate = 1
WorkMomentPermissionCanSee = 2
WorkMomentPermissionCantSee = 3
// workMoment sdk notification type
WorkMomentCommentNotification = 0
WorkMomentLikeNotification = 1
WorkMomentAtUserNotification = 2
// sendMsgStaus
MsgStatusNotExist = 0
MsgIsSending = 1

View File

@ -13,6 +13,7 @@ var (
ErrUserIDNotFound = &ErrInfo{UserIDNotFoundError, "UserIDNotFoundError", ""}
ErrGroupIDNotFound = &ErrInfo{GroupIDNotFoundError, "GroupIDNotFoundError", ""}
ErrGroupIDExisted = &ErrInfo{GroupIDNotFoundError, "GroupIDExisted", ""} // todo group id 已存在
ErrRecordNotFound = &ErrInfo{RecordNotFoundError, "RecordNotFoundError", ""}

View File

@ -20,21 +20,25 @@ const (
superGroupRecvMsgNotNotifyUserIDsKey = "SUPER_GROUP_RECV_MSG_NOT_NOTIFY_USER_IDS:"
conversationExpireTime = time.Second * 60 * 60 * 12
)
type FuncDB func() (string, error)
// args fn will exec when no data in cache
type ConversationCache interface {
// get user's conversationIDs from cache
GetUserConversationIDs(ctx context.Context, userID string, fn func(ctx context.Context, userID string) ([]string, error)) ([]string, error)
GetUserConversationIDs(ctx context.Context, userID string, fn FuncDB) ([]string, error)
// del user's conversationIDs from cache, call when a user add or reduce a conversation
DelUserConversationIDs(ctx context.Context, userID string) error
DelUsersConversationIDs(ctx context.Context,userIDList []string)error
// get one conversation from cache
GetConversation(ctx context.Context, ownerUserID, conversationID string, fn func(ctx context.Context, ownerUserID, conversationID string) (*relationTb.ConversationModel, error)) (*relationTb.ConversationModel, error)
GetConversation(ctx context.Context, ownerUserID, conversationID string, fn FuncDB) (*relationTb.ConversationModel, error)
// get one conversation from cache
GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string, fn func(ctx context.Context, ownerUserID, conversationIDs []string) ([]*relationTb.ConversationModel, error)) ([]*relationTb.ConversationModel, error)
GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string, fn FuncDB)([]*relationTb.ConversationModel, error)
// get one user's all conversations from cache
GetUserAllConversations(ctx context.Context, ownerUserID string, fn func(ctx context.Context, ownerUserIDs string) ([]*relationTb.ConversationModel, error)) ([]*relationTb.ConversationModel, error)
GetUserAllConversations(ctx context.Context, ownerUserID string, fn FuncDB ) ([]*relationTb.ConversationModel, error)
// del one conversation from cache, call when one user's conversation Info changed
DelConversation(ctx context.Context, ownerUserID, conversationID string) error
DelUserConversations(ctx context.Context, ownerUserID string, conversationIDList []string) error
DelUsersConversation(ctx context.Context, ownerUserIDList []string, conversationID string) error
// get user conversation recv msg from cache
GetUserRecvMsgOpt(ctx context.Context, ownerUserID, conversationID string, fn func(ctx context.Context, ownerUserID, conversationID string) (opt int, err error)) (opt int, err error)
// del user recv msg opt from cache, call when user's conversation recv msg opt changed
@ -51,6 +55,38 @@ type ConversationRedis struct {
rcClient *rockscache.Client
}
func (c *ConversationRedis) GetUserConversationIDs(ctx context.Context, userID string, fn func(ctx context.Context, userID string) ([]string, error)) ([]string, error) {
panic("implement me")
}
func (c *ConversationRedis) DelUsersConversationIDs(ctx context.Context, userIDList []string) error {
panic("implement me")
}
func (c *ConversationRedis) GetConversation(ctx context.Context, ownerUserID, conversationID string, fn func(ctx context.Context, ownerUserID string, conversationID string) (*relationTb.ConversationModel, error)) (*relationTb.ConversationModel, error) {
panic("implement me")
}
func (c *ConversationRedis) GetConversations(ctx context.Context, ownerUserID string, conversationIDs []string, fn FuncDB) ([]*relationTb.ConversationModel, error) {
panic("implement me")
}
func (c *ConversationRedis) GetUserAllConversations(ctx context.Context, ownerUserID string, fn FuncDB) ([]*relationTb.ConversationModel, error) {
panic("implement me")
}
func (c *ConversationRedis) DelUsersConversation(ctx context.Context, ownerUserIDList []string, conversationID string) error {
panic("implement me")
}
func (c *ConversationRedis) GetUserRecvMsgOpt(ctx context.Context, ownerUserID, conversationID string, fn func(ctx context.Context, ownerUserID string, conversationID string) (opt int, err error)) (opt int, err error) {
panic("implement me")
}
func (c *ConversationRedis) GetSuperGroupRecvMsgNotNotifyUserIDs(ctx context.Context, groupID string, fn func(ctx context.Context, groupID string) (userIDs []string, err error)) (userIDs []string, err error) {
panic("implement me")
}
func NewConversationRedis(rcClient *rockscache.Client) *ConversationRedis {
return &ConversationRedis{rcClient: rcClient}
}

View File

@ -1,17 +1,14 @@
package cache
import (
"Open_IM/pkg/common/db/relation"
relationTb "Open_IM/pkg/common/db/table/relation"
"Open_IM/pkg/common/db/unrelation"
"Open_IM/pkg/common/tracelog"
"Open_IM/pkg/utils"
"context"
"encoding/json"
"github.com/dtm-labs/rockscache"
"github.com/go-redis/redis/v8"
"math/big"
"strconv"
"strings"
"time"
)
@ -157,6 +154,27 @@ func (g *GroupCacheRedis) GetGroupMembersHash(ctx context.Context, groupID strin
})
}
func (g *GroupCacheRedis) GetGroupMemberHash1(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error) {
// todo
mapGroupUserIDs, err := g.groupMember.FindJoinUserID(ctx, groupIDs)
if err != nil {
return nil, err
}
res := make(map[string]*relationTb.GroupSimpleUserID)
for _, groupID := range groupIDs {
userIDs := mapGroupUserIDs[groupID]
users := &relationTb.GroupSimpleUserID{}
if len(userIDs) > 0 {
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
users.Hash = bi.Uint64()
}
res[groupID] = users
}
return res, nil
}
func (g *GroupCacheRedis) DelGroupMembersHash(ctx context.Context, groupID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID)
@ -178,111 +196,104 @@ func (g *GroupCacheRedis) DelGroupMemberIDs(ctx context.Context, groupID string)
return g.rcClient.TagAsDeleted(g.getGroupMemberIDsKey(groupID))
}
// JoinedGroups
func (g *GroupCacheRedis) GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error) {
getJoinedGroupIDList := func() (string, error) {
joinedGroupList, err := relation.GetJoinedGroupIDListByUserID(userID)
if err != nil {
return "", err
}
bytes, err := json.Marshal(joinedGroupList)
if err != nil {
return "", utils.Wrap(err, "")
}
return string(bytes), nil
}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "joinedGroupIDs", joinedGroupIDs)
}()
joinedGroupIDListStr, err := g.rcClient.Fetch(g.getJoinedGroupsKey(userID), time.Second*30*60, getJoinedGroupIDList)
if err != nil {
return nil, err
}
err = json.Unmarshal([]byte(joinedGroupIDListStr), &joinedGroupIDs)
return joinedGroupIDs, utils.Wrap(err, "")
}
//// JoinedGroups
//func (g *GroupCacheRedis) GetJoinedGroupIDs(ctx context.Context, userID string) (joinedGroupIDs []string, err error) {
// getJoinedGroupIDList := func() (string, error) {
// joinedGroupList, err := relation.GetJoinedGroupIDListByUserID(userID)
// if err != nil {
// return "", err
// }
// bytes, err := json.Marshal(joinedGroupList)
// if err != nil {
// return "", utils.Wrap(err, "")
// }
// return string(bytes), nil
// }
// defer func() {
// tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "joinedGroupIDs", joinedGroupIDs)
// }()
// joinedGroupIDListStr, err := g.rcClient.Fetch(g.getJoinedGroupsKey(userID), time.Second*30*60, getJoinedGroupIDList)
// if err != nil {
// return nil, err
// }
// err = json.Unmarshal([]byte(joinedGroupIDListStr), &joinedGroupIDs)
// return joinedGroupIDs, utils.Wrap(err, "")
//}
func (g *GroupCacheRedis) DelJoinedGroupIDs(ctx context.Context, userID string) (err error) {
func (g *GroupCacheRedis) DelJoinedGroupID(ctx context.Context, userID string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
}()
return g.rcClient.TagAsDeleted(g.getJoinedGroupsKey(userID))
}
// GetGroupMemberInfo
func (g *GroupCacheRedis) GetGroupMemberInfo(ctx context.Context, groupID, userID string) (groupMember *relation.GroupMember, err error) {
getGroupMemberInfo := func() (string, error) {
groupMemberInfo, err := relation.GetGroupMemberInfoByGroupIDAndUserID(groupID, userID)
if err != nil {
return "", err
}
bytes, err := json.Marshal(groupMemberInfo)
if err != nil {
return "", utils.Wrap(err, "")
}
return string(bytes), nil
}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "userID", userID, "groupMember", *groupMember)
}()
groupMemberInfoStr, err := g.rcClient.Fetch(g.getGroupMemberInfoKey(groupID, userID), time.Second*30*60, getGroupMemberInfo)
if err != nil {
return nil, err
}
groupMember = &relation.GroupMember{}
err = json.Unmarshal([]byte(groupMemberInfoStr), groupMember)
return groupMember, utils.Wrap(err, "")
//func (g *GroupCacheRedis) DelJoinedGroupIDs(ctx context.Context, userIDs []string) (err error) {
// defer func() {
// tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID)
// }()
// for _, userID := range userIDs {
// if err := g.DelJoinedGroupID(ctx, userID); err != nil {
// return err
// }
// }
// return nil
//}
func (g *GroupCacheRedis) GetGroupMemberInfo(ctx context.Context, groupID, userID string) (groupMember *relationTb.GroupMemberModel, err error) {
return GetCache(ctx, g.rcClient, g.getGroupMemberInfoKey(groupID, userID), g.expireTime, func(ctx context.Context) (*relationTb.GroupMemberModel, error) {
return g.groupMember.Take(ctx, groupID, userID)
})
}
func (g *GroupCacheRedis) GetGroupMembersInfo(ctx context.Context, groupID, userIDs []string) (groupMember *relationTb.GroupMemberModel, err error) {
//func (g *GroupCacheRedis) GetGroupMembersInfo(ctx context.Context, groupID, userIDs []string) (groupMember *relationTb.GroupMemberModel, err error) {
//
// return nil, err
//}
return nil, err
}
func (g *GroupCacheRedis) GetGroupMembersInfo(ctx context.Context, count, offset int32, groupID string) (groupMembers []*relation.GroupMember, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "count", count, "offset", offset, "groupID", groupID, "groupMember", groupMembers)
}()
groupMemberIDList, err := g.GetGroupMemberIDs(ctx, groupID)
if err != nil {
return nil, err
}
if count < 0 || offset < 0 {
return nil, nil
}
var groupMemberList []*relation.GroupMember
var start, stop int32
start = offset
stop = offset + count
l := int32(len(groupMemberIDList))
if start > stop {
return nil, nil
}
if start >= l {
return nil, nil
}
if count != 0 {
if stop >= l {
stop = l
}
groupMemberIDList = groupMemberIDList[start:stop]
} else {
if l < 1000 {
stop = l
} else {
stop = 1000
}
groupMemberIDList = groupMemberIDList[start:stop]
}
for _, userID := range groupMemberIDList {
groupMember, err := g.GetGroupMemberInfo(ctx, groupID, userID)
if err != nil {
return
}
groupMembers = append(groupMembers, groupMember)
}
return groupMemberList, nil
}
//func (g *GroupCacheRedis) GetGroupMembersInfo(ctx context.Context, count, offset int32, groupID string) (groupMembers []*relation.GroupMember, err error) {
// defer func() {
// tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "count", count, "offset", offset, "groupID", groupID, "groupMember", groupMembers)
// }()
// groupMemberIDList, err := g.GetGroupMemberIDs(ctx, groupID)
// if err != nil {
// return nil, err
// }
// if count < 0 || offset < 0 {
// return nil, nil
// }
// var groupMemberList []*relation.GroupMember
// var start, stop int32
// start = offset
// stop = offset + count
// l := int32(len(groupMemberIDList))
// if start > stop {
// return nil, nil
// }
// if start >= l {
// return nil, nil
// }
// if count != 0 {
// if stop >= l {
// stop = l
// }
// groupMemberIDList = groupMemberIDList[start:stop]
// } else {
// if l < 1000 {
// stop = l
// } else {
// stop = 1000
// }
// groupMemberIDList = groupMemberIDList[start:stop]
// }
// for _, userID := range groupMemberIDList {
// groupMember, err := g.GetGroupMemberInfo(ctx, groupID, userID)
// if err != nil {
// return
// }
// groupMembers = append(groupMembers, groupMember)
// }
// return groupMemberList, nil
//}
func (g *GroupCacheRedis) DelGroupMemberInfo(ctx context.Context, groupID, userID string) (err error) {
defer func() {
@ -292,23 +303,23 @@ func (g *GroupCacheRedis) DelGroupMemberInfo(ctx context.Context, groupID, userI
}
// groupMemberNum
func (g *GroupCacheRedis) GetGroupMemberNum(ctx context.Context, groupID string) (num int, err error) {
getGroupMemberNum := func() (string, error) {
num, err := relation.GetGroupMemberNumByGroupID(groupID)
if err != nil {
return "", err
}
return strconv.Itoa(int(num)), nil
}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "num", num)
}()
groupMember, err := g.rcClient.Fetch(g.getGroupMemberNumKey(groupID), time.Second*30*60, getGroupMemberNum)
if err != nil {
return 0, err
}
return strconv.Atoi(groupMember)
}
//func (g *GroupCacheRedis) GetGroupMemberNum(ctx context.Context, groupID string) (num int, err error) {
// getGroupMemberNum := func() (string, error) {
// num, err := relation.GetGroupMemberNumByGroupID(groupID)
// if err != nil {
// return "", err
// }
// return strconv.Itoa(int(num)), nil
// }
// defer func() {
// tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "num", num)
// }()
// groupMember, err := g.rcClient.Fetch(g.getGroupMemberNumKey(groupID), time.Second*30*60, getGroupMemberNum)
// if err != nil {
// return 0, err
// }
// return strconv.Atoi(groupMember)
//}
func (g *GroupCacheRedis) DelGroupMemberNum(ctx context.Context, groupID string) (err error) {
defer func() {

View File

@ -1,142 +0,0 @@
package controller
import (
"Open_IM/pkg/common/db/relation"
"gorm.io/gorm"
"time"
)
type AdminCMSInterface interface {
GetActiveUserNum(from, to time.Time) (num int64, err error)
GetIncreaseUserNum(from, to time.Time) (num int64, err error)
GetTotalUserNum() (num int64, err error)
GetTotalUserNumByDate(to time.Time) (num int64, err error)
GetSingleChatMessageNum(from, to time.Time) (num int64, err error)
GetGroupMessageNum(from, to time.Time) (num int64, err error)
GetIncreaseGroupNum(from, to time.Time) (num int64, err error)
GetTotalGroupNum() (num int64, err error)
GetGroupNum(to time.Time) (num int64, err error)
GetActiveGroups(from, to time.Time, limit int) (activeGroups []*relation.ActiveGroup, err error)
GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error)
}
type AdminCMSController struct {
database AdminCMSDatabaseInterface
}
func NewAdminCMSController(db *gorm.DB) AdminCMSInterface {
adminCMSController := &AdminCMSController{
database: newAdminCMSDatabase(db),
}
return adminCMSController
}
func newAdminCMSDatabase(db *gorm.DB) AdminCMSDatabaseInterface {
return &AdminCMSDatabase{Statistics: relation.NewStatistics(db)}
}
func (admin *AdminCMSController) GetActiveUserNum(from, to time.Time) (num int64, err error) {
return admin.database.GetActiveUserNum(from, to)
}
func (admin *AdminCMSController) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
return admin.database.GetIncreaseUserNum(from, to)
}
func (admin *AdminCMSController) GetTotalUserNum() (num int64, err error) {
return admin.database.GetTotalUserNum()
}
func (admin *AdminCMSController) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
return admin.database.GetTotalUserNumByDate(to)
}
func (admin *AdminCMSController) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
return admin.GetSingleChatMessageNum(from, to)
}
func (admin *AdminCMSController) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
return admin.database.GetGroupMessageNum(from, to)
}
func (admin *AdminCMSController) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
return admin.database.GetIncreaseGroupNum(from, to)
}
func (admin *AdminCMSController) GetTotalGroupNum() (num int64, err error) {
return admin.database.GetTotalGroupNum()
}
func (admin *AdminCMSController) GetGroupNum(to time.Time) (num int64, err error) {
return admin.database.GetGroupNum(to)
}
func (admin *AdminCMSController) GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error) {
return admin.database.GetActiveGroups(from, to, limit)
}
func (admin *AdminCMSController) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error) {
return admin.database.GetActiveUsers(from, to, limit)
}
type AdminCMSDatabaseInterface interface {
GetActiveUserNum(from, to time.Time) (num int64, err error)
GetIncreaseUserNum(from, to time.Time) (num int64, err error)
GetTotalUserNum() (num int64, err error)
GetTotalUserNumByDate(to time.Time) (num int64, err error)
GetSingleChatMessageNum(from, to time.Time) (num int64, err error)
GetGroupMessageNum(from, to time.Time) (num int64, err error)
GetIncreaseGroupNum(from, to time.Time) (num int64, err error)
GetTotalGroupNum() (num int64, err error)
GetGroupNum(to time.Time) (num int64, err error)
GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error)
GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error)
}
type AdminCMSDatabase struct {
Statistics *relation.Statistics
}
func (admin *AdminCMSDatabase) GetActiveUserNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetActiveUserNum(from, to)
}
func (admin *AdminCMSDatabase) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetIncreaseUserNum(from, to)
}
func (admin *AdminCMSDatabase) GetTotalUserNum() (num int64, err error) {
return admin.Statistics.GetTotalUserNum()
}
func (admin *AdminCMSDatabase) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
return admin.Statistics.GetTotalUserNumByDate(to)
}
func (admin *AdminCMSDatabase) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetSingleChatMessageNum(from, to)
}
func (admin *AdminCMSDatabase) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetGroupMessageNum(from, to)
}
func (admin *AdminCMSDatabase) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetIncreaseGroupNum(from, to)
}
func (admin *AdminCMSDatabase) GetTotalGroupNum() (num int64, err error) {
return admin.Statistics.GetTotalGroupNum()
}
func (admin *AdminCMSDatabase) GetGroupNum(to time.Time) (num int64, err error) {
return admin.Statistics.GetGroupNum(to)
}
func (admin *AdminCMSDatabase) GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error) {
return admin.Statistics.GetActiveGroups(from, to, limit)
}
func (admin *AdminCMSDatabase) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error) {
return admin.Statistics.GetActiveUsers(from, to, limit)
}

View File

@ -1,32 +1,42 @@
package controller
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/cache"
"Open_IM/pkg/common/db/relation"
relationTb "Open_IM/pkg/common/db/table/relation"
"Open_IM/pkg/utils"
"context"
"encoding/json"
"gorm.io/gorm"
)
type ConversationInterface interface {
//GetUserIDExistConversation 获取拥有该会话的的用户ID列表
GetUserIDExistConversation(ctx context.Context, userIDList []string, conversationID string) ([]string, error)
//UpdateUserConversationFiled 更新用户该会话的属性信息
UpdateUsersConversationFiled(ctx context.Context, UserIDList []string, conversationID string, args map[string]interface{}) error
UpdateUsersConversationFiled(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}) error
//CreateConversation 创建一批新的会话
CreateConversation(ctx context.Context, conversations []*relationTb.ConversationModel) error
//SyncPeerUserPrivateConversation 同步对端私聊会话内部保证事务操作
SyncPeerUserPrivateConversationTx(ctx context.Context, conversation *relationTb.ConversationModel) error
//FindConversations 根据会话ID获取某个用户的多个会话
FindConversations(ctx context.Context, ownerUserID string, conversationID []string) ([]*relationTb.ConversationModel, error)
FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error)
//GetUserAllConversation 获取一个用户在服务器上所有的会话
GetUserAllConversation(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error)
//SetUserConversations 设置用户多个会话属性,如果会话不存在则创建,否则更新,内部保证原子性
SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error
//SetUsersConversationFiledTx 设置多个用户会话关于某个字段的更新操作,如果会话不存在则创建,否则更新,内部保证事务操作
SetUsersConversationFiledTx(ctx context.Context, userIDList []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) error
}
type ConversationController struct {
database ConversationDataBaseInterface
}
func (c *ConversationController) SetUsersConversationFiledTx(ctx context.Context, userIDList []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) error {
return c.database.SetUsersConversationFiledTx(ctx, userIDList, conversation, filedMap)
}
func NewConversationController(database ConversationDataBaseInterface) *ConversationController {
return &ConversationController{database: database}
}
@ -36,26 +46,26 @@ func (c *ConversationController) GetUserIDExistConversation(ctx context.Context,
}
func (c ConversationController) UpdateUsersConversationFiled(ctx context.Context, UserIDList []string, conversationID string, args map[string]interface{}) error {
panic("implement me")
return c.database.UpdateUsersConversationFiled(ctx, UserIDList, conversationID, args)
}
func (c ConversationController) CreateConversation(ctx context.Context, conversations []*relationTb.ConversationModel) error {
panic("implement me")
return c.database.CreateConversation(ctx, conversations)
}
func (c ConversationController) SyncPeerUserPrivateConversationTx(ctx context.Context, conversation *relationTb.ConversationModel) error {
panic("implement me")
return c.database.SyncPeerUserPrivateConversationTx(ctx, conversation)
}
func (c ConversationController) FindConversations(ctx context.Context, ownerUserID string, conversationID []string) ([]*relationTb.ConversationModel, error) {
panic("implement me")
func (c ConversationController) FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) {
return c.database.FindConversations(ctx, ownerUserID, conversationIDs)
}
func (c ConversationController) GetUserAllConversation(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error) {
panic("implement me")
return c.database.GetUserAllConversation(ctx, ownerUserID)
}
func (c ConversationController) SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error {
panic("implement me")
return c.database.SetUserConversations(ctx, ownerUserID, conversations)
}
var _ ConversationInterface = (*ConversationController)(nil)
@ -70,19 +80,69 @@ type ConversationDataBaseInterface interface {
//SyncPeerUserPrivateConversation 同步对端私聊会话内部保证事务操作
SyncPeerUserPrivateConversationTx(ctx context.Context, conversation *relationTb.ConversationModel) error
//FindConversations 根据会话ID获取某个用户的多个会话
FindConversations(ctx context.Context, ownerUserID string, conversationID []string) ([]*relationTb.ConversationModel, error)
FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error)
//GetUserAllConversation 获取一个用户在服务器上所有的会话
GetUserAllConversation(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error)
//SetUserConversations 设置用户多个会话属性,如果会话不存在则创建,否则更新,内部保证原子性
SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error
//SetUsersConversationFiledTx 设置多个用户会话关于某个字段的更新操作,如果会话不存在则创建,否则更新,内部保证事务操作
SetUsersConversationFiledTx(ctx context.Context, userIDList []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) error
}
var _ ConversationDataBaseInterface = (*ConversationDataBase)(nil)
type ConversationDataBase struct {
db relation.Conversation
cache cache.ConversationCache
conversationDB relation.Conversation
cache cache.ConversationCache
db *gorm.DB
}
func (c ConversationDataBase) SetUsersConversationFiledTx(ctx context.Context, userIDList []string, conversation *relationTb.ConversationModel, filedMap map[string]interface{}) error {
return c.db.Transaction(func(tx *gorm.DB) error {
haveUserID, err := c.conversationDB.FindUserID(ctx, userIDList, conversation.ConversationID, tx)
if err != nil {
return err
}
if len(haveUserID) > 0 {
err = c.conversationDB.UpdateByMap(ctx, haveUserID, conversation.ConversationID, filedMap, tx)
if err != nil {
return err
}
}
NotUserID := utils.DifferenceString(haveUserID, userIDList)
var cList []*relationTb.ConversationModel
for _, v := range NotUserID {
temp := new(relationTb.ConversationModel)
if err := utils.CopyStructFields(temp, conversation); err != nil {
return err
}
temp.OwnerUserID = v
cList = append(cList, temp)
}
err = c.conversationDB.Create(ctx, cList)
if err != nil {
return err
}
if len(NotUserID) > 0 {
err = c.cache.DelUsersConversationIDs(ctx, NotUserID)
if err != nil {
return err
}
}
err = c.cache.DelUsersConversation(ctx, haveUserID, conversation.ConversationID)
if err != nil {
return err
}
return nil
})
}
func NewConversationDataBase(db relation.Conversation, cache cache.ConversationCache) *ConversationDataBase {
return &ConversationDataBase{conversationDB: db, cache: cache}
}
func (c ConversationDataBase) GetUserIDExistConversation(ctx context.Context, userIDList []string, conversationID string) ([]string, error) {
panic("implement me")
}
func (c ConversationDataBase) UpdateUsersConversationFiled(ctx context.Context, UserIDList []string, conversationID string, args map[string]interface{}) error {
@ -94,26 +154,155 @@ func (c ConversationDataBase) CreateConversation(ctx context.Context, conversati
}
func (c ConversationDataBase) SyncPeerUserPrivateConversationTx(ctx context.Context, conversation *relationTb.ConversationModel) error {
panic("implement me")
return c.db.Transaction(func(tx *gorm.DB) error {
userIDList := []string{conversation.OwnerUserID, conversation.UserID}
haveUserID, err := c.conversationDB.FindUserID(ctx, userIDList, conversation.ConversationID, tx)
if err != nil {
return err
}
filedMap := map[string]interface{}{"is_private_chat": conversation.IsPrivateChat}
if len(haveUserID) > 0 {
err = c.conversationDB.UpdateByMap(ctx, haveUserID, conversation.ConversationID, filedMap, tx)
if err != nil {
return err
}
}
NotUserID := utils.DifferenceString(haveUserID, userIDList)
var cList []*relationTb.ConversationModel
for _, v := range NotUserID {
temp := new(relationTb.ConversationModel)
if v == conversation.UserID {
temp.OwnerUserID = conversation.UserID
temp.ConversationID = utils.GetConversationIDBySessionType(conversation.OwnerUserID, constant.SingleChatType)
temp.ConversationType = constant.SingleChatType
temp.UserID = conversation.OwnerUserID
temp.IsPrivateChat = conversation.IsPrivateChat
} else {
if err := utils.CopyStructFields(temp, conversation); err != nil {
return err
}
temp.OwnerUserID = v
}
cList = append(cList, temp)
}
if len(NotUserID) > 0 {
err = c.conversationDB.Create(ctx, cList)
if err != nil {
return err
}
}
err = c.cache.DelUsersConversationIDs(ctx, NotUserID)
if err != nil {
return err
}
err = c.cache.DelUsersConversation(ctx, haveUserID, conversation.ConversationID)
if err != nil {
return err
}
return nil
})
}
func (c ConversationDataBase) FindConversations(ctx context.Context, ownerUserID string, conversationID []string) ([]*relationTb.ConversationModel, error) {
panic("implement me")
func (c ConversationDataBase) FindConversations(ctx context.Context, ownerUserID string, conversationIDs []string) ([]*relationTb.ConversationModel, error) {
getConversation := func() (string, error) {
conversationList, err := c.conversationDB.Find(ctx, ownerUserID, conversationIDs)
if err != nil {
return "", utils.Wrap(err, "get failed")
}
bytes, err := json.Marshal(conversationList)
if err != nil {
return "", utils.Wrap(err, "Marshal failed")
}
return string(bytes), nil
}
return c.cache.GetConversations(ctx, ownerUserID, conversationIDs, getConversation)
}
func (c ConversationDataBase) GetConversation(ctx context.Context, ownerUserID string, conversationID string) (*relationTb.ConversationModel, error) {
getConversation := func() (string, error) {
conversationList, err := c.conversationDB.Take(ctx, ownerUserID, conversationID)
if err != nil {
return "", utils.Wrap(err, "get failed")
}
bytes, err := json.Marshal(conversationList)
if err != nil {
return "", utils.Wrap(err, "Marshal failed")
}
return string(bytes), nil
}
return c.cache.GetConversation(ctx, ownerUserID, conversationID, getConversation)
}
func (c ConversationDataBase) GetUserAllConversation(ctx context.Context, ownerUserID string) ([]*relationTb.ConversationModel, error) {
panic("implement me")
getConversationIDList := func() (string, error) {
conversationIDList, err := c.conversationDB.FindUserIDAllConversationID(ctx, ownerUserID)
if err != nil {
return "", utils.Wrap(err, "getConversationIDList failed")
}
bytes, err := json.Marshal(conversationIDList)
if err != nil {
return "", utils.Wrap(err, "")
}
return string(bytes), nil
}
conversationIDList, err := c.cache.GetUserConversationIDs(ctx, ownerUserID, getConversationIDList)
if err != nil {
return nil, err
}
var conversations []*relationTb.ConversationModel
for _, conversationID := range conversationIDList {
conversation, tErr := c.GetConversation(ctx, ownerUserID, conversationID)
if tErr != nil {
return nil, utils.Wrap(tErr, "GetConversation failed")
}
conversations = append(conversations, conversation)
}
return conversations, nil
}
func (c ConversationDataBase) SetUserConversations(ctx context.Context, ownerUserID string, conversations []*relationTb.ConversationModel) error {
panic("implement me")
}
return c.db.Transaction(func(tx *gorm.DB) error {
var conversationIDList []string
for _, conversation := range conversations {
conversationIDList = append(conversationIDList, conversation.ConversationID)
}
haveConversations, err := c.conversationDB.Find(ctx, ownerUserID, conversationIDList, tx)
if err != nil {
return err
}
if len(haveConversations) > 0 {
err = c.conversationDB.Update(ctx, conversations, tx)
if err != nil {
return err
}
}
var haveConversationID []string
for _, conversation := range haveConversations {
haveConversationID = append(haveConversationID, conversation.ConversationID)
}
func NewConversationDataBase(db relation.Conversation, cache cache.ConversationCache) *ConversationDataBase {
return &ConversationDataBase{db: db, cache: cache}
NotConversationID := utils.DifferenceString(haveConversationID, conversationIDList)
var NotConversations []*relationTb.ConversationModel
for _, conversation := range conversations {
if !utils.IsContain(conversation.ConversationID, haveConversationID) {
NotConversations = append(NotConversations, conversation)
}
}
if len(NotConversations) > 0 {
err = c.conversationDB.Create(ctx, NotConversations)
if err != nil {
return err
}
}
err = c.cache.DelUsersConversationIDs(ctx, NotConversationID)
if err != nil {
return err
}
err = c.cache.DelUserConversations(ctx, ownerUserID, haveConversationID)
if err != nil {
return err
}
return nil
})
}
//func NewConversationController(db *gorm.DB, rdb redis.UniversalClient) ConversationInterface {
// groupController := &ConversationController{database: newGroupDatabase(db, rdb, mgoClient)}
// return groupController
//}

View File

@ -15,8 +15,6 @@ import (
"github.com/go-redis/redis/v8"
"go.mongodb.org/mongo-driver/mongo"
"gorm.io/gorm"
"math/big"
"strings"
)
//type GroupInterface GroupDataBaseInterface
@ -248,7 +246,7 @@ type GroupDataBase struct {
func (g *GroupDataBase) delGroupMemberCache(ctx context.Context, groupID string, userIDs []string) error {
for _, userID := range userIDs {
if err := g.cache.DelJoinedGroupIDs(ctx, userID); err != nil {
if err := g.cache.DelJoinedGroupID(ctx, userID); err != nil {
return err
}
if err := g.cache.DelJoinedSuperGroupIDs(ctx, userID); err != nil {
@ -272,21 +270,24 @@ func (g *GroupDataBase) FindGroupMemberUserID(ctx context.Context, groupID strin
}
func (g *GroupDataBase) CreateGroup(ctx context.Context, groups []*relationTb.GroupModel, groupMembers []*relationTb.GroupMemberModel) error {
if len(groups) > 0 && len(groupMembers) > 0 {
return g.db.Transaction(func(tx *gorm.DB) error {
return g.db.Transaction(func(tx *gorm.DB) error {
if len(groups) > 0 {
if err := g.groupDB.Create(ctx, groups, tx); err != nil {
return err
}
return g.groupMemberDB.Create(ctx, groupMembers, tx)
})
}
if len(groups) > 0 {
return g.groupDB.Create(ctx, groups)
}
if len(groupMembers) > 0 {
return g.groupMemberDB.Create(ctx, groupMembers)
}
return nil
}
if len(groupMembers) > 0 {
if err := g.groupMemberDB.Create(ctx, groupMembers, tx); err != nil {
return err
}
//if err := g.cache.DelJoinedGroupIDs(ctx, utils.Slice(groupMembers, func(e *relationTb.GroupMemberModel) string {
// return e.UserID
//})); err != nil {
// return err
//}
}
return nil
})
}
func (g *GroupDataBase) TakeGroup(ctx context.Context, groupID string) (group *relationTb.GroupModel, err error) {
@ -337,12 +338,11 @@ func (g *GroupDataBase) TakeGroupMember(ctx context.Context, groupID string, use
}
func (g *GroupDataBase) TakeGroupOwner(ctx context.Context, groupID string) (*relationTb.GroupMemberModel, error) {
return g.groupMemberDB.TakeOwner(ctx, groupID)
return g.groupMemberDB.TakeOwner(ctx, groupID) // todo cache group owner
}
func (g *GroupDataBase) FindGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32) ([]*relationTb.GroupMemberModel, error) {
//g.cache.GetGroupMembersInfo()
return g.groupMemberDB.Find(ctx, groupIDs, userIDs, roleLevels)
return g.groupMemberDB.Find(ctx, groupIDs, userIDs, roleLevels) // todo cache group find
}
func (g *GroupDataBase) PageGroupMember(ctx context.Context, groupIDs []string, userIDs []string, roleLevels []int32, pageNumber, showNumber int32) (uint32, []*relationTb.GroupMemberModel, error) {
@ -383,23 +383,7 @@ func (g *GroupDataBase) DeleteGroupMember(ctx context.Context, groupID string, u
}
func (g *GroupDataBase) MapGroupMemberUserID(ctx context.Context, groupIDs []string) (map[string]*relationTb.GroupSimpleUserID, error) {
mapGroupUserIDs, err := g.groupMemberDB.FindJoinUserID(ctx, groupIDs)
if err != nil {
return nil, err
}
res := make(map[string]*relationTb.GroupSimpleUserID)
for _, groupID := range groupIDs {
userIDs := mapGroupUserIDs[groupID]
users := &relationTb.GroupSimpleUserID{}
if len(userIDs) > 0 {
utils.Sort(userIDs, true)
bi := big.NewInt(0)
bi.SetString(utils.Md5(strings.Join(userIDs, ";"))[0:8], 16)
users.Hash = bi.Uint64()
}
res[groupID] = users
}
return res, nil
return g.cache.GetGroupMemberHash1(ctx, groupIDs)
}
func (g *GroupDataBase) MapGroupMemberNum(ctx context.Context, groupIDs []string) (map[string]uint32, error) {

View File

@ -8,10 +8,12 @@ import (
type MsgInterface interface {
BatchInsertChat2DB(ctx context.Context, userID string, msgList []*pbMsg.MsgDataToMQ, currentMaxSeq uint64) error
BatchInsertChat2Cache(ctx context.Context, insertID string, msgList []*pbMsg.MsgDataToMQ) (error, uint64)
DelMsgBySeqList(ctx context.Context, userID string, seqList []uint32) (totalUnExistSeqList []uint32, err error)
DelMsgLogic(ctx context.Context, uid string, seqList []uint32) error
// logic delete
DelMsgLogic(ctx context.Context, userID string, seqList []uint32) error
DelMsgBySeqListInOneDoc(ctx context.Context, docID string, seqList []uint32) (unExistSeqList []uint32, err error)
ReplaceMsgToBlankByIndex(suffixID string, index int) (replaceMaxSeq uint32, err error)
ReplaceMsgToBlankByIndex(docID string, index int) (replaceMaxSeq uint32, err error)
}
type MsgDatabaseInterface interface {

View File

@ -30,11 +30,11 @@ type UserController struct {
}
// 获取指定用户的信息 如有userID未找到 也返回错误
func (u *UserController) FindWithError(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserController) FindWithError(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
return u.database.FindWithError(ctx, userIDs)
}
func (u *UserController) Find(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserController) Find(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
return u.database.Find(ctx, userIDs)
}
func (u *UserController) Create(ctx context.Context, users []*relationTb.UserModel) error {
@ -90,7 +90,7 @@ func newUserDatabase(db *gorm.DB) *UserDatabase {
}
// 获取指定用户的信息 如有userID未找到 也返回错误
func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
users, err = u.user.Find(ctx, userIDs)
if err != nil {
return
@ -102,7 +102,7 @@ func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (use
}
// 获取指定用户的信息 如有userID未找到 不返回错误
func (u *UserDatabase) Find(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserDatabase) Find(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
users, err = u.user.Find(ctx, userIDs)
return
}
@ -123,7 +123,7 @@ func (u *UserDatabase) UpdateByMap(ctx context.Context, userID string, args map[
}
// 获取,如果没找到,不返回错误
func (u *UserDatabase) Page(ctx context.Context, showNumber, pageNumber int32) (users []*relation2.UserModel, count int64, err error) {
func (u *UserDatabase) Page(ctx context.Context, showNumber, pageNumber int32) (users []*relationTb.UserModel, count int64, err error) {
return u.user.Page(ctx, showNumber, pageNumber)
}

View File

@ -1,7 +1,7 @@
package relation
import (
"Open_IM/pkg/common/db/table"
"Open_IM/pkg/common/db/table/relation"
"Open_IM/pkg/common/tracelog"
"Open_IM/pkg/utils"
"context"
@ -10,12 +10,15 @@ import (
type Conversation interface {
TableName() string
Create(ctx context.Context, conversations []*table.ConversationModel) (err error)
Create(ctx context.Context, conversations []*relation.ConversationModel, tx ...any) (err error)
Delete(ctx context.Context, groupIDs []string) (err error)
UpdateByMap(ctx context.Context, groupID string, args map[string]interface{}) (err error)
Update(ctx context.Context, groups []*table.ConversationModel) (err error)
Find(ctx context.Context, groupIDs []string) (groups []*table.ConversationModel, err error)
Take(ctx context.Context, groupID string) (group *table.ConversationModel, err error)
UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}, tx ...any) (err error)
Update(ctx context.Context, conversations []*relation.ConversationModel, tx ...any) (err error)
Find(ctx context.Context, ownerUserID string, conversationIDs []string, tx ...any) (conversations []*relation.ConversationModel, err error)
FindUserID(ctx context.Context, userIDList []string, conversationID string, tx ...any) ([]string, error)
FindUserIDAllConversationID(ctx context.Context, userID string, tx ...any) ([]string, error)
Take(ctx context.Context, userID, conversationID string, tx ...any) (conversation *relation.ConversationModel, err error)
FindConversationID(ctx context.Context, userID string, conversationIDList []string, tx ...any) (existConversationID []string, err error)
}
type ConversationGorm struct {
DB *gorm.DB
@ -29,45 +32,69 @@ func NewConversationGorm(DB *gorm.DB) Conversation {
return &ConversationGorm{DB: DB}
}
func (c *ConversationGorm) Create(ctx context.Context, conversations []*table.ConversationModel) (err error) {
func (c *ConversationGorm) Create(ctx context.Context, conversations []*relation.ConversationModel, tx ...any) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "conversations", conversations)
}()
return utils.Wrap(getDBConn(g.DB, tx).Create(&conversations).Error, "")
return utils.Wrap(getDBConn(c.DB, tx).Create(&conversations).Error, "")
}
func (c *ConversationGorm) Delete(ctx context.Context, groupIDs []string) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs)
}()
return utils.Wrap(getDBConn(g.DB, tx).Where("group_id in (?)", groupIDs).Delete(&table.ConversationModel{}).Error, "")
return utils.Wrap(getDBConn(g.DB, tx).Where("group_id in (?)", groupIDs).Delete(&relation.ConversationModel{}).Error, "")
}
func (c *ConversationGorm) UpdateByMap(ctx context.Context, groupID string, args map[string]interface{}) (err error) {
func (c *ConversationGorm) UpdateByMap(ctx context.Context, userIDList []string, conversationID string, args map[string]interface{}, tx ...any) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "args", args)
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userIDList", userIDList, "conversationID", conversationID)
}()
return utils.Wrap(getDBConn(g.DB, tx).Where("group_id = ?", groupID).Model(g).Updates(args).Error, "")
return utils.Wrap(getDBConn(c.DB, tx).Model(&relation.ConversationModel{}).Where("owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Updates(args).Error, "")
}
func (c *ConversationGorm) Update(ctx context.Context, groups []*table.ConversationModel) (err error) {
func (c *ConversationGorm) Update(ctx context.Context, conversations []*relation.ConversationModel, tx ...any) (err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groups", groups)
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "conversations", conversations)
}()
return utils.Wrap(getDBConn(g.DB, tx).Updates(&groups).Error, "")
return utils.Wrap(getDBConn(c.DB, tx).Updates(&conversations).Error, "")
}
func (c *ConversationGorm) Find(ctx context.Context, groupIDs []string) (groups []*table.ConversationModel, err error) {
func (c *ConversationGorm) Find(ctx context.Context, ownerUserID string, conversationIDs []string, tx ...any) (conversations []*relation.ConversationModel, err error) {
var newConversations []relation.ConversationModel
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupIDs", groupIDs, "groups", groups)
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "ownerUserID", ownerUserID, "groups", conversations)
}()
return groups, utils.Wrap(getDBConn(g.DB, tx).Where("group_id in (?)", groupIDs).Find(&groups).Error, "")
err = utils.Wrap(getDBConn(c.DB, tx).Where("owner_user_id=? and conversation_id IN (?)", ownerUserID, conversationIDs).Find(&newConversations).Error, "")
for _, v := range newConversations {
v1 := v
conversations = append(conversations, &v1)
}
return conversations, err
}
func (c *ConversationGorm) Take(ctx context.Context, groupID string) (group *table.ConversationModel, err error) {
group = &Group{}
func (c *ConversationGorm) Take(ctx context.Context, userID, conversationID string, tx ...any) (conversation *relation.ConversationModel, err error) {
cc := &relation.ConversationModel{}
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "groupID", groupID, "group", *group)
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "conversation", *conversation)
}()
return group, utils.Wrap(getDBConn(g.DB, tx).Where("group_id = ?", groupID).Take(group).Error, "")
return cc, utils.Wrap(getDBConn(c.DB, tx).Where("conversation_id = ? And owner_user_id = ?", conversationID, userID).Take(cc).Error, "")
}
func (c *ConversationGorm) FindUserID(ctx context.Context, userIDList []string, conversationID string, tx ...any) (existUserID []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userIDList, "existUserID", existUserID)
}()
return existUserID, utils.Wrap(getDBConn(c.DB, tx).Where(" owner_user_id IN (?) and conversation_id=?", userIDList, conversationID).Pluck("owner_user_id", &existUserID).Error, "")
}
func (c *ConversationGorm) FindConversationID(ctx context.Context, userID string, conversationIDList []string, tx ...any) (existConversationID []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "existConversationIDList", existConversationID)
}()
return existConversationID, utils.Wrap(getDBConn(c.DB, tx).Where(" conversation_id IN (?) and owner_user_id=?", conversationIDList, userID).Pluck("conversation_id", &existConversationID).Error, "")
}
func (c *ConversationGorm) FindUserIDAllConversationID(ctx context.Context, userID string, tx ...any) (conversationIDList []string, err error) {
defer func() {
tracelog.SetCtxDebug(ctx, utils.GetFuncName(1), err, "userID", userID, "conversationIDList", conversationIDList)
}()
return conversationIDList, utils.Wrap(getDBConn(c.DB, tx).Model(&relation.ConversationModel{}).Where("owner_user_id=?", userID).Pluck("conversation_id", &conversationIDList).Error, "")
}

View File

@ -1,100 +0,0 @@
package relation
import (
"Open_IM/pkg/common/config"
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Mysql struct {
gormConn *gorm.DB
}
func (m *Mysql) GormConn() *gorm.DB {
return m.gormConn
}
func (m *Mysql) SetGormConn(gormConn *gorm.DB) {
m.gormConn = gormConn
}
func (m *Mysql) InitConn() *Mysql {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], "mysql")
var db *gorm.DB
db, err := gorm.Open(mysql.Open(dsn), nil)
if err != nil {
time.Sleep(time.Duration(30) * time.Second)
db, err = gorm.Open(mysql.Open(dsn), nil)
if err != nil {
panic(err.Error() + " open failed " + dsn)
}
}
sql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8 COLLATE utf8_general_ci;", config.Config.Mysql.DBDatabaseName)
err = db.Exec(sql).Error
if err != nil {
panic(err.Error() + " Exec failed:" + sql)
}
dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], config.Config.Mysql.DBDatabaseName)
newLogger := logger.New(
Writer{},
logger.Config{
SlowThreshold: time.Duration(config.Config.Mysql.SlowThreshold) * time.Millisecond, // Slow SQL threshold
LogLevel: logger.LogLevel(config.Config.Mysql.LogLevel), // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: true, // Disable color
},
)
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
if err != nil {
panic(err.Error() + " Open failed " + dsn)
}
sqlDB, err := db.DB()
if err != nil {
panic(err.Error() + " DB.DB() failed ")
}
sqlDB.SetConnMaxLifetime(time.Second * time.Duration(config.Config.Mysql.DBMaxLifeTime))
sqlDB.SetMaxOpenConns(config.Config.Mysql.DBMaxOpenConns)
sqlDB.SetMaxIdleConns(config.Config.Mysql.DBMaxIdleConns)
if db == nil {
panic("db is nil")
}
m.SetGormConn(db)
return m
}
//models := []interface{}{&Friend{}, &FriendRequest{}, &Group{}, &GroupMember{}, &GroupRequest{},
// &User{}, &Black{}, &ChatLog{}, &Conversation{}, &AppVersion{}}
func (m *Mysql) AutoMigrateModel(model interface{}) error {
err := m.gormConn.AutoMigrate(model)
if err != nil {
return err
}
m.gormConn.Set("gorm:table_options", "CHARSET=utf8")
m.gormConn.Set("gorm:table_options", "collation=utf8_unicode_ci")
_ = m.gormConn.Migrator().CreateTable(model)
return nil
}
type Writer struct{}
func (w Writer) Printf(format string, args ...interface{}) {
fmt.Printf(format, args...)
}
func getDBConn(db *gorm.DB, tx []any) *gorm.DB {
if len(tx) > 0 {
if txDB, ok := tx[0].(*gorm.DB); ok {
return txDB
}
}
return db
}

View File

@ -1,101 +0,0 @@
package relation
import (
"Open_IM/pkg/common/constant"
"gorm.io/gorm"
"time"
)
type Statistics struct {
DB *gorm.DB
}
func NewStatistics(db *gorm.DB) *Statistics {
return &Statistics{DB: db}
}
func (s *Statistics) getUserModel() *gorm.DB {
return s.DB.Model(&User{})
}
func (s *Statistics) getChatLogModel() *gorm.DB {
return s.DB.Model(&ChatLog{})
}
func (s *Statistics) getGroupModel() *gorm.DB {
return s.DB.Model(&Group{})
}
func (s *Statistics) GetActiveUserNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Select("count(distinct(send_id))").Where("send_time >= ? and send_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
err = s.getUserModel().Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalUserNum() (num int64, err error) {
err = s.getUserModel().Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
err = s.getUserModel().Where("create_time <= ?", to).Count(&num).Error
return num, err
}
func (s *Statistics) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Where("send_time >= ? and send_time <= ? and session_type = ?", from, to, constant.SingleChatType).Count(&num).Error
return num, err
}
func (s *Statistics) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.GroupChatType, constant.SuperGroupChatType}).Count(&num).Error
return num, err
}
func (s *Statistics) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
err = s.getGroupModel().Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalGroupNum() (num int64, err error) {
err = s.getGroupModel().Count(&num).Error
return num, err
}
func (s *Statistics) GetGroupNum(to time.Time) (num int64, err error) {
err = s.getGroupModel().Where("create_time <= ?", to).Count(&num).Error
return num, err
}
func (s *Statistics) GetActiveGroups(from, to time.Time, limit int) ([]*ActiveGroup, error) {
var activeGroups []*ActiveGroup
err := s.getChatLogModel().Select("recv_id, count(*) as message_num").Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.GroupChatType, constant.SuperGroupChatType}).Group("recv_id").Limit(limit).Order("message_num DESC").Find(&activeGroups).Error
for _, activeGroup := range activeGroups {
group := Group{
GroupID: activeGroup.ID,
}
s.getGroupModel().Where("group_id= ? ", group.GroupID).Find(&group)
activeGroup.Name = group.GroupName
}
return activeGroups, err
}
func (s *Statistics) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*ActiveUser, err error) {
err = s.getChatLogModel().Select("send_id, count(*) as message_num").Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.SingleChatType, constant.GroupChatType, constant.SuperGroupChatType}).Group("send_id").Limit(limit).Order("message_num DESC").Find(&activeUsers).Error
for _, activeUser := range activeUsers {
user := User{
UserID: activeUser.ID,
}
err = s.getUserModel().Select("user_id, name").Find(&user).Error
if err != nil {
return nil, err
}
activeUser.Name = user.Nickname
activeUser.ID = user.UserID
}
return activeUsers, err
}

View File

@ -49,6 +49,20 @@ func (u UserMsgDocModel) GetSeqUid(uid string, seq uint32) string {
return u.getSeqUid(uid, seq)
}
func (u UserMsgDocModel) GetDocIDSeqsMap(uid string, seqs []uint32) map[string][]uint32 {
t := make(map[string][]uint32)
for i := 0; i < len(seqs); i++ {
seqUid := u.getSeqUid(uid, seqs[i])
if value, ok := t[seqUid]; !ok {
var temp []uint32
t[seqUid] = append(temp, seqs[i])
} else {
t[seqUid] = append(value, seqs[i])
}
}
return t
}
func (UserMsgDocModel) getMsgIndex(seq uint32) int {
seqSuffix := seq / singleGocMsgNum
var index uint32

View File

@ -1,42 +0,0 @@
package unrelation
import "context"
const (
CTag = "tag"
CSendLog = "send_log"
)
type TagModel struct {
UserID string `bson:"user_id"`
TagID string `bson:"tag_id"`
TagName string `bson:"tag_name"`
UserList []string `bson:"user_list"`
}
func (TagModel) TableName() string {
return CTag
}
type TagSendLogModel struct {
UserList []CommonUserModel `bson:"tag_list"`
SendID string `bson:"send_id"`
SenderPlatformID int32 `bson:"sender_platform_id"`
Content string `bson:"content"`
SendTime int64 `bson:"send_time"`
}
func (TagSendLogModel) TableName() string {
return CSendLog
}
type TagModelInterface interface {
GetUserTags(ctx context.Context, userID string) ([]TagModel, error)
CreateTag(ctx context.Context, userID, tagName string, userList []string) error
GetTagByID(ctx context.Context, userID, tagID string) (TagModel, error)
DeleteTag(ctx context.Context, userID, tagID string) error
SetTag(ctx context.Context, userID, tagID, newName string, increaseUserIDList []string, reduceUserIDList []string) error
GetUserIDListByTagID(ctx context.Context, userID, tagID string) ([]string, error)
SaveTagSendLog(ctx context.Context, tagSendLog *TagSendLogModel) error
GetTagSendLogs(ctx context.Context, userID string, showNumber, pageNumber int32) ([]TagSendLogModel, error)
}

View File

@ -1,48 +0,0 @@
package unrelation
import "context"
const (
CWorkMoment = "work_moment"
)
type WorkMoment struct {
WorkMomentID string `bson:"work_moment_id"`
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
FaceURL string `bson:"face_url"`
Content string `bson:"content"`
LikeUserList []*CommonUserModel `bson:"like_user_list"`
AtUserList []*CommonUserModel `bson:"at_user_list"`
PermissionUserList []*CommonUserModel `bson:"permission_user_list"`
Comments []*CommonUserModel `bson:"comments"`
PermissionUserIDList []string `bson:"permission_user_id_list"`
Permission int32 `bson:"permission"`
CreateTime int32 `bson:"create_time"`
}
type Comment struct {
UserID string `bson:"user_id" json:"user_id"`
UserName string `bson:"user_name" json:"user_name"`
ReplyUserID string `bson:"reply_user_id" json:"reply_user_id"`
ReplyUserName string `bson:"reply_user_name" json:"reply_user_name"`
ContentID string `bson:"content_id" json:"content_id"`
Content string `bson:"content" json:"content"`
CreateTime int32 `bson:"create_time" json:"create_time"`
}
func (WorkMoment) TableName() string {
return CWorkMoment
}
type WorkMomentModelInterface interface {
CreateOneWorkMoment(ctx context.Context, workMoment *WorkMoment) error
DeleteOneWorkMoment(ctx context.Context, workMomentID string) error
DeleteComment(ctx context.Context, workMomentID, contentID, opUserID string) error
GetWorkMomentByID(ctx context.Context, workMomentID string) (*WorkMoment, error)
LikeOneWorkMoment(ctx context.Context, likeUserID, userName, workMomentID string) (*WorkMoment, bool, error)
CommentOneWorkMoment(ctx context.Context, comment *Comment, workMomentID string) (*WorkMoment, error)
GetUserSelfWorkMoments(ctx context.Context, userID string, showNumber, pageNumber int32) ([]*WorkMoment, error)
GetUserWorkMoments(ctx context.Context, opUserID, userID string, showNumber, pageNumber int32, friendIDList []string) ([]*WorkMoment, error)
GetUserFriendWorkMoments(ctx context.Context, showNumber, pageNumber int32, userID string, friendIDList []string) ([]*WorkMoment, error)
}

View File

@ -61,20 +61,8 @@ func (m *Mongo) GetClient() *mongo.Client {
return m.db
}
func (m *Mongo) CreateTagIndex() {
if err := m.createMongoIndex(unrelation.CSendLog, false, "send_id", "-send_time"); err != nil {
panic(err.Error() + " index create failed " + unrelation.CSendLog + " send_id, -send_time")
}
if err := m.createMongoIndex(unrelation.CTag, false, "user_id", "-create_time"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CTag + " user_id, -create_time")
}
if err := m.createMongoIndex(unrelation.CTag, true, "tag_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CTag + " tag_id")
}
}
func (m *Mongo) CreateMsgIndex() {
if err := m.createMongoIndex(unrelation.CChat, false, "uid"); err != nil {
if err := m.createMongoIndex(unrelation, false, "uid"); err != nil {
fmt.Println(err.Error() + " index create failed " + unrelation.CChat + " uid, please create index by yourself in field uid")
}
}
@ -88,21 +76,9 @@ func (m *Mongo) CreateSuperGroupIndex() {
}
}
func (m *Mongo) CreateWorkMomentIndex() {
if err := m.createMongoIndex(unrelation.CWorkMoment, true, "-create_time", "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " -create_time, work_moment_id")
}
if err := m.createMongoIndex(unrelation.CWorkMoment, true, "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " work_moment_id ")
}
if err := m.createMongoIndex(unrelation.CWorkMoment, false, "user_id", "-create_time"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + "user_id, -create_time")
}
}
func (m *Mongo) CreateExtendMsgSetIndex() {
if err := m.createMongoIndex(unrelation.CExtendMsgSet, true, "-create_time", "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " -create_time, work_moment_id")
panic(err.Error() + "index create failed " + unrelation.CExtendMsgSet + " -create_time, work_moment_id")
}
}

View File

@ -69,7 +69,7 @@ package unrelation
// return nil
//}
//func (d *db.DataBases) ReplaceMsgByIndex(suffixUserID string, msg *open_im_sdk.MsgData, operationID string, seqIndex int) error {
//func (d *db.DataBases) ReplaceMsgByIndex(suffixUserID string, msg *sdkws.MsgData, operationID string, seqIndex int) error {
// log.NewInfo(operationID, utils.GetSelfFuncName(), suffixUserID, *msg)
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@ -90,7 +90,7 @@ package unrelation
// return nil
//}
//func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
//func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *sdkws.MsgData, operationID string) error {
// log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@ -122,7 +122,7 @@ package unrelation
// return err
//}
//
//func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// log.NewInfo(operationID, utils.GetSelfFuncName(), uid, seqList)
// var hasSeqList []uint32
// singleCount := 0
@ -153,7 +153,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
// return nil, err
@ -217,11 +217,11 @@ package unrelation
// }
// for i, msg := range userChat.Msg {
// if i <= index {
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// if err = proto.Unmarshal(msg.Msg, msgPb); err != nil {
// continue
// }
// newMsgPb := &open_im_sdk.MsgData{Seq: msgPb.Seq}
// newMsgPb := &sdkws.MsgData{Seq: msgPb.Seq}
// bytes, err := proto.Marshal(newMsgPb)
// if err != nil {
// continue
@ -235,7 +235,7 @@ package unrelation
// return replaceMaxSeq, err
//}
//
//func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetNewestMsg(ID string) (msg *sdkws.MsgData, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// regex := fmt.Sprintf("^%s", ID)
@ -251,7 +251,7 @@ package unrelation
// }
// if len(userChats) > 0 {
// if len(userChats[0].Msg) > 0 {
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// err = proto.Unmarshal(userChats[0].Msg[len(userChats[0].Msg)-1].Msg, msgPb)
// if err != nil {
// return nil, utils.Wrap(err, "")
@ -263,7 +263,7 @@ package unrelation
// return nil, nil
//}
//
//func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetOldestMsg(ID string) (msg *sdkws.MsgData, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// regex := fmt.Sprintf("^%s", ID)
@ -288,7 +288,7 @@ package unrelation
// if len(oldestMsg) == 0 {
// oldestMsg = userChats[0].Msg[len(userChats[0].Msg)-1].Msg
// }
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// err = proto.Unmarshal(oldestMsg, msgPb)
// if err != nil {
// return nil, utils.Wrap(err, "")
@ -298,7 +298,7 @@ package unrelation
// return nil, nil
//}
//
//func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// var hasSeqList []uint32
// singleCount := 0
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@ -325,7 +325,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
// return nil, err
@ -349,7 +349,7 @@ package unrelation
// }
// return seqMsg, nil
//}
//func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// var hasSeqList []uint32
// singleCount := 0
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@ -376,7 +376,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, groupID, seqList, err.Error())
// return nil, err
@ -401,7 +401,7 @@ package unrelation
// return seqMsg, nil
//}
//
//func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, indexList []int, unexistSeqList []uint32, err error) {
//func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, indexList []int, unexistSeqList []uint32, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// sChat := UserChat{}
@ -412,7 +412,7 @@ package unrelation
// singleCount := 0
// var hasSeqList []uint32
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", msg.String(), err.Error())
// return nil, nil, nil, err
@ -436,18 +436,18 @@ package unrelation
// return seqMsg, indexList, unexistSeqList, nil
//}
//
//func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
//func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*sdkws.MsgData) {
// for _, v := range seqList {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// msg.Seq = v
// exceptionMsg = append(exceptionMsg, msg)
// }
// return exceptionMsg
//}
//
//func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*open_im_sdk.MsgData) {
//func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*sdkws.MsgData) {
// for _, v := range seqList {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// msg.Seq = v
// msg.GroupID = groupID
// msg.SessionType = constant.SuperGroupChatType
@ -598,13 +598,7 @@ package unrelation
// return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func generateWorkMomentID(userID string) string {
// return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func generateWorkMomentCommentID(workMomentID string) string {
// return utils.Md5(workMomentID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func getCurrentTimestampByMill() int64 {
// return time.Now().UnixNano() / 1e6

View File

@ -121,7 +121,7 @@ func (m *MsgMongoDriver) ReplaceMsgByIndex(ctx context.Context, suffixUserID str
return nil
}
func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *sdkws.MsgData, operationID string) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@ -153,7 +153,7 @@ func (d *db.DataBases) UpdateOneMsgList(msg *UserChat) error {
return err
}
func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, seqList)
var hasSeqList []uint32
singleCount := 0
@ -184,7 +184,7 @@ func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
@ -209,10 +209,11 @@ func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID
return seqMsg, nil
}
func (d *db.DataBases) GetUserMsgListByIndex(ID string, index int64) (*UserChat, error) {
// model
func (d *db.DataBases) GetUserMsgListByIndex(docID string, index int64) (*UserChat, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
regex := fmt.Sprintf("^%s", docID)
findOpts := options.Find().SetLimit(1).SetSkip(index).SetSort(bson.M{"uid": 1})
var msgs []UserChat
//primitive.Regex{Pattern: regex}
@ -231,6 +232,7 @@ func (d *db.DataBases) GetUserMsgListByIndex(ID string, index int64) (*UserChat,
}
}
// model
func (d *db.DataBases) DelMongoMsgs(IDList []string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@ -238,6 +240,7 @@ func (d *db.DataBases) DelMongoMsgs(IDList []string) error {
return err
}
// model
func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (replaceMaxSeq uint32, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@ -248,11 +251,11 @@ func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (rep
}
for i, msg := range userChat.Msg {
if i <= index {
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
if err = proto.Unmarshal(msg.Msg, msgPb); err != nil {
continue
}
newMsgPb := &open_im_sdk.MsgData{Seq: msgPb.Seq}
newMsgPb := &sdkws.MsgData{Seq: msgPb.Seq}
bytes, err := proto.Marshal(newMsgPb)
if err != nil {
continue
@ -266,7 +269,7 @@ func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (rep
return replaceMaxSeq, err
}
func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetNewestMsg(ID string) (msg *sdkws.MsgData, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
@ -282,7 +285,7 @@ func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err er
}
if len(userChats) > 0 {
if len(userChats[0].Msg) > 0 {
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
err = proto.Unmarshal(userChats[0].Msg[len(userChats[0].Msg)-1].Msg, msgPb)
if err != nil {
return nil, utils.Wrap(err, "")
@ -294,7 +297,7 @@ func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err er
return nil, nil
}
func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetOldestMsg(ID string) (msg *sdkws.MsgData, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
@ -319,7 +322,7 @@ func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err er
if len(oldestMsg) == 0 {
oldestMsg = userChats[0].Msg[len(userChats[0].Msg)-1].Msg
}
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
err = proto.Unmarshal(oldestMsg, msgPb)
if err != nil {
return nil, utils.Wrap(err, "")
@ -329,7 +332,7 @@ func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err er
return nil, nil
}
func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
var hasSeqList []uint32
singleCount := 0
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@ -356,7 +359,7 @@ func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, opera
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
@ -380,7 +383,7 @@ func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, opera
}
return seqMsg, nil
}
func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
var hasSeqList []uint32
singleCount := 0
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@ -407,7 +410,7 @@ func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, groupID, seqList, err.Error())
return nil, err
@ -432,7 +435,7 @@ func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []
return seqMsg, nil
}
func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, indexList []int, unexistSeqList []uint32, err error) {
func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, indexList []int, unexistSeqList []uint32, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
sChat := UserChat{}
@ -443,7 +446,7 @@ func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, s
singleCount := 0
var hasSeqList []uint32
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", msg.String(), err.Error())
return nil, nil, nil, err
@ -467,18 +470,18 @@ func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, s
return seqMsg, indexList, unexistSeqList, nil
}
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*sdkws.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
msg.Seq = v
exceptionMsg = append(exceptionMsg, msg)
}
return exceptionMsg
}
func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*open_im_sdk.MsgData) {
func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*sdkws.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
msg.Seq = v
msg.GroupID = groupID
msg.SessionType = constant.SuperGroupChatType

View File

@ -1,117 +0,0 @@
package unrelation
import (
"Open_IM/pkg/common/db/table/unrelation"
"Open_IM/pkg/utils"
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
"strconv"
"time"
)
type TagMongoDriver struct {
mgoDB *mongo.Database
TagCollection *mongo.Collection
TagSendLogCollection *mongo.Collection
}
func NewTagMongoDriver(mgoDB *mongo.Database) *TagMongoDriver {
return &TagMongoDriver{mgoDB: mgoDB, TagCollection: mgoDB.Collection(unrelation.CTag), TagSendLogCollection: mgoDB.Collection(unrelation.CSendLog)}
}
func (db *TagMongoDriver) generateTagID(tagName, userID string) string {
return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *TagMongoDriver) GetUserTags(ctx context.Context, userID string) ([]unrelation.TagModel, error) {
var tags []unrelation.TagModel
cursor, err := db.TagCollection.Find(ctx, bson.M{"user_id": userID})
if err != nil {
return tags, err
}
if err = cursor.All(ctx, &tags); err != nil {
return tags, err
}
return tags, nil
}
func (db *TagMongoDriver) CreateTag(ctx context.Context, userID, tagName string, userList []string) error {
tagID := generateTagID(tagName, userID)
tag := unrelation.TagModel{
UserID: userID,
TagID: tagID,
TagName: tagName,
UserList: userList,
}
_, err := db.TagCollection.InsertOne(ctx, tag)
return err
}
func (db *TagMongoDriver) GetTagByID(ctx context.Context, userID, tagID string) (unrelation.TagModel, error) {
var tag unrelation.TagModel
err := db.TagCollection.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag, err
}
func (db *TagMongoDriver) DeleteTag(ctx context.Context, userID, tagID string) error {
_, err := db.TagCollection.DeleteOne(ctx, bson.M{"user_id": userID, "tag_id": tagID})
return err
}
func (db *TagMongoDriver) SetTag(ctx context.Context, userID, tagID, newName string, increaseUserIDList []string, reduceUserIDList []string) error {
var tag unrelation.TagModel
if err := db.TagCollection.FindOne(ctx, bson.M{"tag_id": tagID, "user_id": userID}).Decode(&tag); err != nil {
return err
}
if newName != "" {
_, err := db.TagCollection.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"tag_name": newName}})
if err != nil {
return err
}
}
tag.UserList = append(tag.UserList, increaseUserIDList...)
tag.UserList = utils.RemoveRepeatedStringInList(tag.UserList)
for _, v := range reduceUserIDList {
for i2, v2 := range tag.UserList {
if v == v2 {
tag.UserList[i2] = ""
}
}
}
var newUserList []string
for _, v := range tag.UserList {
if v != "" {
newUserList = append(newUserList, v)
}
}
_, err := db.TagCollection.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"user_list": newUserList}})
if err != nil {
return err
}
return nil
}
func (db *TagMongoDriver) GetUserIDListByTagID(ctx context.Context, userID, tagID string) ([]string, error) {
var tag unrelation.TagModel
err := db.TagCollection.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag.UserList, err
}
func (db *TagMongoDriver) SaveTagSendLog(ctx context.Context, tagSendLog *unrelation.TagSendLogModel) error {
_, err := db.TagSendLogCollection.InsertOne(ctx, tagSendLog)
return err
}
func (db *TagMongoDriver) GetTagSendLogs(ctx context.Context, userID string, showNumber, pageNumber int32) ([]unrelation.TagSendLogModel, error) {
var tagSendLogs []unrelation.TagSendLogModel
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"send_time": -1})
cursor, err := db.TagSendLogCollection.Find(ctx, bson.M{"send_id": userID}, findOpts)
if err != nil {
return tagSendLogs, err
}
err = cursor.All(ctx, &tagSendLogs)
return tagSendLogs, err
}

View File

@ -1,151 +0,0 @@
package unrelation
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/table/unrelation"
"Open_IM/pkg/utils"
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
"strconv"
"time"
)
type WorkMomentMongoDriver struct {
mgoDB *mongo.Database
WorkMomentCollection *mongo.Collection
}
func NewWorkMomentMongoDriver(mgoDB *mongo.Database) *WorkMomentMongoDriver {
return &WorkMomentMongoDriver{mgoDB: mgoDB, WorkMomentCollection: mgoDB.Collection(unrelation.CWorkMoment)}
}
func (db *WorkMomentMongoDriver) generateWorkMomentID(userID string) string {
return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *WorkMomentMongoDriver) generateWorkMomentCommentID(workMomentID string) string {
return utils.Md5(workMomentID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *WorkMomentMongoDriver) CreateOneWorkMoment(ctx context.Context, workMoment *unrelation.WorkMoment) error {
workMomentID := db.generateWorkMomentID(workMoment.UserID)
workMoment.WorkMomentID = workMomentID
workMoment.CreateTime = int32(time.Now().Unix())
_, err := db.WorkMomentCollection.InsertOne(ctx, workMoment)
return err
}
func (db *WorkMomentMongoDriver) DeleteOneWorkMoment(ctx context.Context, workMomentID string) error {
_, err := db.WorkMomentCollection.DeleteOne(ctx, bson.M{"work_moment_id": workMomentID})
return err
}
func (db *WorkMomentMongoDriver) DeleteComment(ctx context.Context, workMomentID, contentID, opUserID string) error {
_, err := db.WorkMomentCollection.UpdateOne(ctx, bson.D{{"work_moment_id", workMomentID},
{"$or", bson.A{
bson.D{{"user_id", opUserID}},
bson.D{{"comments", bson.M{"$elemMatch": bson.M{"user_id": opUserID}}}},
},
}}, bson.M{"$pull": bson.M{"comments": bson.M{"content_id": contentID}}})
return err
}
func (db *WorkMomentMongoDriver) GetWorkMomentByID(ctx context.Context, workMomentID string) (*unrelation.WorkMoment, error) {
workMoment := &unrelation.WorkMoment{}
err := db.WorkMomentCollection.FindOne(ctx, bson.M{"work_moment_id": workMomentID}).Decode(workMoment)
return workMoment, err
}
func (db *WorkMomentMongoDriver) LikeOneWorkMoment(ctx context.Context, likeUserID, userName, workMomentID string) (*unrelation.WorkMoment, bool, error) {
workMoment, err := db.GetWorkMomentByID(ctx, workMomentID)
if err != nil {
return nil, false, err
}
var isAlreadyLike bool
for i, user := range workMoment.LikeUserList {
if likeUserID == user.UserID {
isAlreadyLike = true
workMoment.LikeUserList = append(workMoment.LikeUserList[0:i], workMoment.LikeUserList[i+1:]...)
}
}
if !isAlreadyLike {
workMoment.LikeUserList = append(workMoment.LikeUserList, &unrelation.CommonUserModel{UserID: likeUserID, UserName: userName})
}
_, err = db.WorkMomentCollection.UpdateOne(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$set": bson.M{"like_user_list": workMoment.LikeUserList}})
return workMoment, !isAlreadyLike, err
}
func (db *WorkMomentMongoDriver) CommentOneWorkMoment(ctx context.Context, comment *unrelation.Comment, workMomentID string) (unrelation.WorkMoment, error) {
comment.ContentID = generateWorkMomentCommentID(workMomentID)
var workMoment unrelation.WorkMoment
err := db.WorkMomentCollection.FindOneAndUpdate(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$push": bson.M{"comments": comment}}).Decode(&workMoment)
return workMoment, err
}
func (db *WorkMomentMongoDriver) GetUserSelfWorkMoments(ctx context.Context, userID string, showNumber, pageNumber int32) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := db.WorkMomentCollection.Find(ctx, bson.M{"user_id": userID}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (db *WorkMomentMongoDriver) GetUserWorkMoments(ctx context.Context, opUserID, userID string, showNumber, pageNumber int32, friendIDList []string) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := db.WorkMomentCollection.Find(ctx, bson.D{ // 等价条件: select * from
{"user_id", userID},
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{opUserID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{opUserID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}},
}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (db *WorkMomentMongoDriver) GetUserFriendWorkMoments(ctx context.Context, showNumber, pageNumber int32, userID string, friendIDList []string) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
var filter bson.D
permissionFilter := bson.D{
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}}}
if config.Config.WorkMoment.OnlyFriendCanSee {
filter = bson.D{
{"$or", bson.A{
bson.D{{"user_id", userID}}, //self
bson.D{{"$and", bson.A{permissionFilter, bson.D{{"user_id", bson.D{{"$in", friendIDList}}}}}}},
},
},
}
} else {
filter = bson.D{
{"$or", bson.A{
bson.D{{"user_id", userID}}, //self
permissionFilter,
},
},
}
}
result, err := db.WorkMomentCollection.Find(ctx, filter, findOpts)
if err != nil {
return workMomentList, err
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}

File diff suppressed because it is too large Load Diff

View File

@ -1,175 +0,0 @@
syntax = "proto3";
option go_package = "Open_IM/pkg/proto/admincms;admincms";
import "Open-IM-Server/pkg/proto/sdkws/ws.proto";
package admincms;
message AdminLoginReq {
string adminID = 2;
string secret = 3;
}
message AdminLoginResp {
string token = 1;
string userName = 2;
string faceURL = 3;
}
message GetChatLogsReq {
string content = 1;
string sendID = 2;
string recvID = 3;
string sendTime = 4;
int32 sessionType = 5;
int32 contentType = 6;
sdkws.RequestPagination pagination = 7;
}
message ChatLog {
string serverMsgID = 1;
string clientMsgID = 2;
string sendID = 3;
string recvID = 4;
string groupID = 5;
string recvNickname = 6;
int32 senderPlatformID = 7;
string senderNickname = 8;
string senderFaceURL = 9;
string groupName = 10;
int32 sessionType = 11;
int32 msgFrom = 12;
int32 contentType = 13;
string content = 14;
int32 status = 15;
int64 sendTime = 16;
int64 createTime = 17;
string ex = 18;
}
message GetChatLogsResp {
repeated ChatLog chatLogs = 1;
int32 chatLogsNum = 2;
}
message StatisticsReq {
string from = 1;
string to = 2;
}
message GetActiveUserReq{
StatisticsReq statisticsReq = 1;
}
message UserResp{
string nickName = 1;
string userID = 2;
int32 messageNum = 3;
}
message GetActiveUserResp {
repeated UserResp Users = 1;
}
message GetActiveGroupReq{
StatisticsReq statisticsReq = 1;
}
message GroupResp {
string GroupName = 1;
string GroupID = 2;
int32 MessageNum = 3;
}
message GetActiveGroupResp {
repeated GroupResp Groups = 1;
}
message DateNumList {
string Date = 1;
int32 Num = 2;
}
message GetMessageStatisticsReq {
StatisticsReq StatisticsReq = 1;
}
message GetMessageStatisticsResp {
int32 PrivateMessageNum = 1;
int32 GroupMessageNum = 2;
repeated DateNumList PrivateMessageNumList = 3;
repeated DateNumList GroupMessageNumList = 4;
}
message GetGroupStatisticsReq {
StatisticsReq StatisticsReq = 1;
}
message GetGroupStatisticsResp {
int32 IncreaseGroupNum = 1;
int32 TotalGroupNum = 2;
repeated DateNumList IncreaseGroupNumList = 3;
repeated DateNumList TotalGroupNumList = 4;
}
message GetUserStatisticsReq {
StatisticsReq StatisticsReq = 1;
string OperationID = 2;
}
message GetUserStatisticsResp {
int32 IncreaseUserNum = 1;
int32 ActiveUserNum = 2;
int32 TotalUserNum = 3;
repeated DateNumList IncreaseUserNumList = 4;
repeated DateNumList ActiveUserNumList = 5;
repeated DateNumList TotalUserNumList = 6;
}
message GetUserFriendsReq {
string operationID = 1;
string userID = 2;
string friendUserID = 3;
string friendUserName = 4;
sdkws.RequestPagination pagination = 5;
}
message GetUserFriendsResp {
repeated sdkws.FriendInfo friendInfoList = 2;
int32 friendNums = 3;
}
message GetUserIDByEmailAndPhoneNumberReq{
string email = 2;
string phoneNumber = 3;
}
message GetUserIDByEmailAndPhoneNumberResp{
repeated string userIDList = 1;
}
message GetUserTokenReq {
string userID = 1;
int32 platformID = 2;
}
message GetUserTokenResp {
string token = 1;
int64 expTime = 2;
}
service adminCMS {
rpc AdminLogin(AdminLoginReq) returns(AdminLoginResp);
rpc GetChatLogs(GetChatLogsReq) returns(GetChatLogsResp);
rpc GetActiveUser(GetActiveUserReq) returns(GetActiveUserResp);
rpc GetActiveGroup(GetActiveGroupReq) returns(GetActiveGroupResp);
rpc GetMessageStatistics(GetMessageStatisticsReq) returns(GetMessageStatisticsResp);
rpc GetGroupStatistics(GetGroupStatisticsReq) returns(GetGroupStatisticsResp);
rpc GetUserStatistics(GetUserStatisticsReq) returns(GetUserStatisticsResp);
rpc GetUserFriends(GetUserFriendsReq) returns(GetUserFriendsResp);
rpc GetUserIDByEmailAndPhoneNumber(GetUserIDByEmailAndPhoneNumberReq) returns(GetUserIDByEmailAndPhoneNumberResp);
rpc GetUserToken(GetUserTokenReq) returns(GetUserTokenResp);
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More