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

pull/141/head
Gordon 3 years ago
commit d610b19f4e

1
.gitignore vendored

@ -5,6 +5,7 @@ components
logs
out-test
.github
.idea
deploy/open_im_demo
deploy/open_im_api

@ -1 +1 @@
Subproject commit a85c10dbffbb797b5b2091e209ff67a5534b9bfc
Subproject commit e43ec7d427a84702eea7a6aaa358a7a0a809019d

@ -0,0 +1,15 @@
package main
import (
"Open_IM/internal/cms_api"
"Open_IM/pkg/utils"
"github.com/gin-gonic/gin"
)
func main() {
gin.SetMode(gin.ReleaseMode)
router := cms_api.NewGinRouter()
router.Use(utils.CorsHandler())
router.Run(":" + "8000")
}

@ -0,0 +1,14 @@
package main
import (
rpcMessageCMS "Open_IM/internal/rpc/admin_cms"
"flag"
)
func main() {
rpcPort := flag.Int("port", 11000, "rpc listening port")
flag.Parse()
rpcServer := rpcMessageCMS.NewAdminCMSServer(*rpcPort)
rpcServer.Run()
}

@ -0,0 +1,13 @@
package main
import (
rpcMessageCMS "Open_IM/internal/rpc/message_cms"
"flag"
)
func main() {
rpcPort := flag.Int("port", 10900, "rpc listening port")
flag.Parse()
rpcServer := rpcMessageCMS.NewMessageCMSServer(*rpcPort)
rpcServer.Run()
}

@ -0,0 +1,13 @@
package main
import (
"Open_IM/internal/rpc/statistics"
"flag"
)
func main() {
rpcPort := flag.Int("port", 10800, "rpc listening port")
flag.Parse()
rpcServer := statistics.NewStatisticsServer(*rpcPort)
rpcServer.Run()
}

@ -8,10 +8,10 @@ etcd:
etcdAddr: [ 127.0.0.1:2379 ]
mysql:
dbMysqlAddress: [ 127.0.0.1:13306 ]
dbMysqlAddress: [ 43.128.5.63:13306 ]
dbMysqlUserName: root
dbMysqlPassword: openIM
dbMysqlDatabaseName: openIM
dbMysqlDatabaseName: openIMtest1
dbTableName: eMsg
dbMsgTableNum: 1
dbMaxOpenConns: 20
@ -19,7 +19,7 @@ mysql:
dbMaxLifeTime: 120
mongo:
dbAddress: [ 127.0.0.1:37017 ]
dbAddress: [ 43.128.5.63:37017 ]
dbDirect: false
dbTimeout: 10
dbDatabase: openIM
@ -30,7 +30,7 @@ mongo:
dbRetainChatRecords: 7
redis:
dbAddress: 127.0.0.1:16379
dbAddress: 43.128.5.63:16379
dbMaxIdle: 128
dbMaxActive: 0
dbIdleTimeout: 120
@ -70,6 +70,8 @@ endpoints:
api:
openImApiPort: [ 10000 ]
cmsapi:
openImCMSPort: [ 8000 ]
sdk:
openImSdkWsPort: [ 30000 ]
@ -90,6 +92,9 @@ rpcport:
openImGroupPort: [ 10500 ]
openImAuthPort: [ 10600 ]
openImPushPort: [ 10700 ]
openImOpenImStatisticPort: [ 10800 ]
OpenImMessageCMSPort: [ 10900 ]
openImAdminCMSPort: [11000]
c2c:
callbackBeforeSendMsg:
switch: false
@ -108,6 +113,9 @@ rpcregistername:
openImOnlineMessageRelayName: OnlineMessageRelay
openImGroupName: Group
openImAuthName: Auth
OpenImStatisticsName: Statistics
OpenImMessageCMSName: MessageCMS
openImAdminCMSName: AdminCMS
log:
storageLocation: ../logs/
@ -144,8 +152,8 @@ push:
pushUrl: "https://api.jpush.cn/v3/push"
pushIntent: "intent:#Intent;component=io.openim.app.enterprisechat/io.openim.app.enterprisechat.MainActivity;end"
manager:
appManagerUid: [ "openIM123456","openIM654321" ]
secrets: [ "openIM1","openIM2" ]
appManagerUid: [ "openIM123456","openIM654321", "openIM333", "openIMAdmin"]
secrets: [ "openIM1","openIM2", "openIM333" ]
secret: tuoyun

@ -47,7 +47,7 @@ require (
golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb
golang.org/x/net v0.0.0-20210917221730-978cfadd31cf
google.golang.org/grpc v1.40.0
google.golang.org/protobuf v1.27.1 // indirect
google.golang.org/protobuf v1.27.1
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22

@ -363,7 +363,6 @@ func GetGroupsInfo(c *gin.Context) {
return
}
log.NewInfo(req.OperationID, "GetGroupsInfo args ", req.String())
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := rpc.NewGroupClient(etcdConn)
RpcResp, err := client.GetGroupsInfo(context.Background(), req)
@ -536,5 +535,4 @@ func TransferGroupOwner(c *gin.Context) {
resp := api.TransferGroupOwnerResp{CommResp: api.CommResp{ErrCode: reply.CommonResp.ErrCode, ErrMsg: reply.CommonResp.ErrMsg}}
log.NewInfo(req.OperationID, "TransferGroupOwner api return ", resp)
c.JSON(http.StatusOK, resp)
}

@ -0,0 +1,42 @@
package admin
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbAdmin "Open_IM/pkg/proto/admin_cms"
"Open_IM/pkg/utils"
"context"
"strings"
"github.com/gin-gonic/gin"
)
// register
func AdminLogin(c *gin.Context) {
var (
req cms_api_struct.AdminLoginRequest
resp cms_api_struct.AdminLoginResponse
reqPb pbAdmin.AdminLoginReq
)
if err := c.BindJSON(&req); err != nil {
log.NewInfo("0", utils.GetSelfFuncName(), err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.Secret = req.Secret
reqPb.AdminID = req.AdminName
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImAdminCMSName)
client := pbAdmin.NewAdminCMSClient(etcdConn)
respPb, err := client.AdminLogin(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "rpc failed", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
resp.Token = respPb.Token
openIMHttp.RespHttp200(c, constant.OK, resp)
}

@ -0,0 +1,450 @@
package group
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
commonPb "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"strings"
pbGroup "Open_IM/pkg/proto/group"
"github.com/gin-gonic/gin"
)
func GetGroupById(c *gin.Context) {
var (
req cms_api_struct.GetGroupByIdRequest
resp cms_api_struct.GetGroupByIdResponse
reqPb pbGroup.GetGroupByIdReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroupById(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetGroupById failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
resp.GroupName = respPb.CMSGroup.GroupInfo.GroupName
resp.GroupID = respPb.CMSGroup.GroupInfo.GroupID
resp.CreateTime = (utils.UnixSecondToTime(int64(respPb.CMSGroup.GroupInfo.CreateTime))).String()
resp.ProfilePhoto = respPb.CMSGroup.GroupInfo.FaceURL
resp.GroupMasterName = respPb.CMSGroup.GroupMasterName
resp.GroupMasterId = respPb.CMSGroup.GroupMasterId
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetGroups(c *gin.Context) {
var (
req cms_api_struct.GetGroupsRequest
resp cms_api_struct.GetGroupsResponse
reqPb pbGroup.GetGroupsReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.Pagination = &commonPb.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroups(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetUserInfo failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
for _, v := range respPb.CMSGroups {
resp.Groups = append(resp.Groups, cms_api_struct.GroupResponse{
GroupName: v.GroupInfo.GroupName,
GroupID: v.GroupInfo.GroupID,
GroupMasterName: v.GroupMasterName,
GroupMasterId: v.GroupMasterId,
CreateTime: (utils.UnixSecondToTime(int64(v.GroupInfo.CreateTime))).String(),
IsBanChat: false,
IsBanPrivateChat: false,
ProfilePhoto: v.GroupInfo.FaceURL,
})
}
resp.GroupNums = int(respPb.GroupNum)
resp.CurrentPage = int(respPb.Pagination.PageNumber)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetGroupByName(c *gin.Context) {
var (
req cms_api_struct.GetGroupRequest
resp cms_api_struct.GetGroupResponse
reqPb pbGroup.GetGroupReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupName = req.GroupName
reqPb.Pagination = &commonPb.RequestPagination{}
utils.CopyStructFields(&reqPb.Pagination, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroup(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetGroup failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
for _, v := range respPb.CMSGroups {
resp.Groups = append(resp.Groups, cms_api_struct.GroupResponse{
GroupName: v.GroupInfo.GroupName,
GroupID: v.GroupInfo.GroupID,
GroupMasterName: v.GroupMasterName,
GroupMasterId: v.GroupMasterId,
CreateTime: (utils.UnixSecondToTime(int64(v.GroupInfo.CreateTime))).String(),
IsBanChat: false,
IsBanPrivateChat: false,
ProfilePhoto: v.GroupInfo.FaceURL,
})
}
resp.CurrentPage = int(respPb.Pagination.PageNumber)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.GroupNums = int(respPb.GroupNums)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func CreateGroup(c *gin.Context) {
var (
req cms_api_struct.CreateGroupRequest
_ cms_api_struct.CreateGroupResponse
reqPb pbGroup.CreateGroupReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupInfo = &commonPb.GroupInfo{}
reqPb.GroupInfo.GroupName = req.GroupName
reqPb.GroupInfo.CreatorUserID = req.GroupMasterId
reqPb.OwnerUserID = req.GroupMasterId
reqPb.OpUserID = req.GroupMasterId
for _, v := range req.GroupMembers {
reqPb.InitMemberList = append(reqPb.InitMemberList, &pbGroup.GroupAddMemberInfo{
UserID: v,
RoleLevel: 1,
})
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.CreateGroup(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "CreateGroup failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func BanGroupChat(c *gin.Context) {
var (
req cms_api_struct.BanGroupChatRequest
reqPb pbGroup.OperateGroupStatusReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupBanChat
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateGroupStatus(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BanGroupChat failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func BanPrivateChat(c *gin.Context) {
var (
req cms_api_struct.BanPrivateChatRequest
reqPb pbGroup.OperateGroupStatusReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupBanPrivateChat
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateGroupStatus(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "OperateGroupStatus failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func OpenGroupChat(c *gin.Context) {
var (
req cms_api_struct.BanPrivateChatRequest
reqPb pbGroup.OperateGroupStatusReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupOk
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateGroupStatus(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "OperateGroupStatus failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func OpenPrivateChat(c *gin.Context) {
var (
req cms_api_struct.BanPrivateChatRequest
reqPb pbGroup.OperateGroupStatusReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "OpenPrivateChat failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.Status = constant.GroupOk
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateGroupStatus(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "OperateGroupStatus failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func GetGroupMembers(c *gin.Context) {
var (
req cms_api_struct.GetGroupMembersRequest
reqPb pbGroup.GetGroupMembersCMSReq
resp cms_api_struct.GetGroupMembersResponse
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.Pagination = &commonPb.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
}
reqPb.GroupId = req.GroupId
reqPb.UserName = req.UserName
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.GetGroupMembersCMS(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetGroupMembersCMS failed:", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
resp.ResponsePagination = cms_api_struct.ResponsePagination{
CurrentPage: int(respPb.Pagination.CurrentPage),
ShowNumber: int(respPb.Pagination.ShowNumber),
}
resp.MemberNums = int(respPb.MemberNums)
for _, groupMembers := range respPb.Members {
resp.GroupMembers = append(resp.GroupMembers, cms_api_struct.GroupMemberResponse{
MemberPosition: int(groupMembers.RoleLevel),
MemberNickName: groupMembers.Nickname,
MemberId: groupMembers.UserID,
JoinTime: utils.UnixSecondToTime(groupMembers.JoinTime).String(),
})
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func AddGroupMembers(c *gin.Context) {
var (
req cms_api_struct.RemoveGroupMembersRequest
resp cms_api_struct.RemoveGroupMembersResponse
reqPb pbGroup.AddGroupMembersCMSReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationId, utils.GetSelfFuncName(),"BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.UserIds = req.Members
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.AddGroupMembersCMS(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationId, utils.GetSelfFuncName(), "AddGroupMembersCMS failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
resp.Success = respPb.Success
resp.Failed = respPb.Failed
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func RemoveGroupMembers(c *gin.Context) {
var (
req cms_api_struct.RemoveGroupMembersRequest
resp cms_api_struct.RemoveGroupMembersResponse
reqPb pbGroup.RemoveGroupMembersCMSReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(),"BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.UserIds = req.Members
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
respPb, err := client.RemoveGroupMembersCMS(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "RemoveGroupMembersCMS failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
resp.Success = respPb.Success
resp.Failed = respPb.Failed
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func DeleteGroup(c *gin.Context) {
var (
req cms_api_struct.DeleteGroupRequest
_ cms_api_struct.DeleteGroupResponse
reqPb pbGroup.DeleteGroupReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(),"BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.DeleteGroup(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "DeleteGroup failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func SetGroupMaster(c *gin.Context) {
var (
req cms_api_struct.SetGroupMasterRequest
_ cms_api_struct.SetGroupMasterResponse
reqPb pbGroup.OperateUserRoleReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(),"BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.UserId = req.UserId
reqPb.RoleLevel = constant.GroupOwner
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateUserRole(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "DeleteGroup failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func SetGroupOrdinaryUsers(c *gin.Context) {
var (
req cms_api_struct.SetGroupMemberRequest
_ cms_api_struct.AdminLoginResponse
reqPb pbGroup.OperateUserRoleReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.GroupId = req.GroupId
reqPb.UserId = req.UserId
reqPb.RoleLevel = constant.GroupOrdinaryUsers
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.OperateUserRole(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "DeleteGroup failed", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func AlterGroupInfo(c *gin.Context) {
var (
req cms_api_struct.AlterGroupInfoRequest
_ cms_api_struct.SetGroupMasterResponse
reqPb pbGroup.SetGroupInfoReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.OpUserID = c.MustGet("userID").(string)
reqPb.GroupInfo = &commonPb.GroupInfo{
GroupID: req.GroupID,
GroupName: req.GroupName,
Introduction: req.Introduction,
Notification: req.Notification,
FaceURL: req.ProfilePhoto,
GroupType: int32(req.GroupType),
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
client := pbGroup.NewGroupClient(etcdConn)
_, err := client.SetGroupInfo(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "DeleteGroup failed", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}

@ -0,0 +1,69 @@
package messageCMS
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbMessage "Open_IM/pkg/proto/message_cms"
pbCommon "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"strings"
"Open_IM/pkg/common/constant"
"github.com/gin-gonic/gin"
)
func BroadcastMessage(c *gin.Context) {
var (
reqPb pbMessage.BoradcastMessageReq
)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImMessageCMSName)
client := pbMessage.NewMessageCMSClient(etcdConn)
_, err := client.BoradcastMessage(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetChatLogs rpc failed", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func MassSendMassage(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func WithdrawMessage(c *gin.Context) {
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func GetChatLogs(c *gin.Context) {
var (
req cms_api_struct.GetChatLogsRequest
resp cms_api_struct.GetChatLogsResponse
reqPb pbMessage.GetChatLogsReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
reqPb.Pagination = &pbCommon.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
}
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImMessageCMSName)
client := pbMessage.NewMessageCMSClient(etcdConn)
respPb, err := client.GetChatLogs(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetChatLogs rpc failed", err.Error())
openIMHttp.RespHttp200(c, err, resp)
return
}
utils.CopyStructFields(&resp, &respPb)
openIMHttp.RespHttp200(c, constant.OK, resp)
}

@ -0,0 +1,23 @@
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
func CorsHandler() gin.HandlerFunc {
return func(context *gin.Context) {
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Methods", "*")
context.Header("Access-Control-Allow-Headers", "*")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar") // 跨域关键设置 让浏览器可以解析
context.Header("Access-Control-Max-Age", "172800") // 缓存请求信息 单位为秒
context.Header("Access-Control-Allow-Credentials", "false") // 跨域请求是否需要带cookie信息 默认设置为true
context.Header("content-type", "application/json") // 设置返回格式是json
//Release all option pre-requests
if context.Request.Method == http.MethodOptions {
context.JSON(http.StatusOK, "Options Request!")
}
context.Next()
}
}

@ -0,0 +1,24 @@
package middleware
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/utils"
"github.com/gin-gonic/gin"
)
func JWTAuth() gin.HandlerFunc {
return func(c *gin.Context) {
ok, userID := token_verify.GetUserIDFromToken(c.Request.Header.Get("token"))
log.NewInfo("0", utils.GetSelfFuncName(), "userID: ", userID)
c.Set("userID", userID)
if !ok {
log.NewError("","GetUserIDFromToken false ", c.Request.Header.Get("token"))
c.Abort()
http.RespHttp200(c, constant.ErrParseToken, nil)
return
}
}
}

@ -0,0 +1,49 @@
package organization
import (
"github.com/gin-gonic/gin"
)
func GetStaffs(c *gin.Context) {
}
func GetOrganizations(c *gin.Context) {
}
func GetSquads(c *gin.Context) {
}
func AlterStaff(c *gin.Context) {
}
func AddOrganization(c *gin.Context) {
}
func InquireOrganization(g *gin.Context) {
}
func AlterOrganization(c *gin.Context) {
}
func DeleteOrganization(g *gin.Context) {
}
func GetOrganizationSquads(c *gin.Context) {
}
func AlterStaffsInfo(c *gin.Context) {
}
func AddChildOrganization(c *gin.Context) {
}

@ -0,0 +1,95 @@
package cms_api
import (
"Open_IM/internal/cms_api/admin"
"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/organization"
"Open_IM/internal/cms_api/statistics"
"Open_IM/internal/cms_api/user"
"github.com/gin-gonic/gin"
)
func NewGinRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
baseRouter := gin.Default()
router := baseRouter.Group("/api")
router.Use(middleware.CorsHandler())
adminRouterGroup := router.Group("/admin")
{
adminRouterGroup.POST("/login", admin.AdminLogin)
}
r2 := router.Group("")
r2.Use(middleware.JWTAuth())
statisticsRouterGroup := r2.Group("/statistics")
{
statisticsRouterGroup.GET("/get_messages_statistics", statistics.GetMessagesStatistics)
statisticsRouterGroup.GET("/get_user_statistics", statistics.GetUserStatistics)
statisticsRouterGroup.GET("/get_group_statistics", statistics.GetGroupStatistics)
statisticsRouterGroup.GET("/get_active_user", statistics.GetActiveUser)
statisticsRouterGroup.GET("/get_active_group", statistics.GetActiveGroup)
}
organizationRouterGroup := r2.Group("/organization")
{
organizationRouterGroup.GET("/get_staffs", organization.GetStaffs)
organizationRouterGroup.GET("/get_organizations", organization.GetOrganizations)
organizationRouterGroup.GET("/get_squad", organization.GetSquads)
organizationRouterGroup.POST("/add_organization", organization.AddOrganization)
organizationRouterGroup.POST("/alter_staff", organization.AlterStaff)
organizationRouterGroup.GET("/inquire_organization", organization.InquireOrganization)
organizationRouterGroup.POST("/alter_organization", organization.AlterOrganization)
organizationRouterGroup.POST("/delete_organization", organization.DeleteOrganization)
organizationRouterGroup.POST("/get_organization_squad", organization.GetOrganizationSquads)
organizationRouterGroup.PATCH("/alter_corps_info", organization.AlterStaffsInfo)
organizationRouterGroup.POST("/add_child_org", organization.AddChildOrganization)
}
groupRouterGroup := r2.Group("/group")
{
groupRouterGroup.GET("/get_group_by_id", group.GetGroupById)
groupRouterGroup.GET("/get_groups", group.GetGroups)
groupRouterGroup.GET("/get_group_by_name", group.GetGroupByName)
groupRouterGroup.GET("/get_group_members", group.GetGroupMembers)
groupRouterGroup.POST("/create_group", group.CreateGroup)
groupRouterGroup.POST("/add_members", group.AddGroupMembers)
groupRouterGroup.POST("/remove_members", group.RemoveGroupMembers)
groupRouterGroup.POST("/ban_group_private_chat", group.BanPrivateChat)
groupRouterGroup.POST("/open_group_private_chat", group.OpenPrivateChat)
groupRouterGroup.POST("/ban_group_chat", group.BanGroupChat)
groupRouterGroup.POST("/open_group_chat", group.OpenGroupChat)
groupRouterGroup.POST("/delete_group", group.DeleteGroup)
groupRouterGroup.POST("/get_members_in_group", group.GetGroupMembers)
groupRouterGroup.POST("/set_group_master", group.SetGroupMaster)
groupRouterGroup.POST("/set_group_ordinary_user", group.SetGroupOrdinaryUsers)
groupRouterGroup.POST("/alter_group_info", group.AlterGroupInfo)
}
userRouterGroup := r2.Group("/user")
{
userRouterGroup.POST("/resign", user.ResignUser)
userRouterGroup.GET("/get_user", user.GetUserById)
userRouterGroup.POST("/alter_user", user.AlterUser)
userRouterGroup.GET("/get_users", user.GetUsers)
userRouterGroup.POST("/add_user", user.AddUser)
userRouterGroup.POST("/unblock_user", user.UnblockUser)
userRouterGroup.POST("/block_user", user.BlockUser)
userRouterGroup.GET("/get_block_users", user.GetBlockUsers)
userRouterGroup.GET("/get_block_user", user.GetBlockUserById)
userRouterGroup.POST("/delete_user", user.DeleteUser)
userRouterGroup.GET("/get_users_by_name", user.GetUsersByName)
}
friendRouterGroup := r2.Group("/friend")
{
friendRouterGroup.POST("/get_friends_by_id")
friendRouterGroup.POST("/set_friend")
friendRouterGroup.POST("/remove_friend")
}
messageCMSRouterGroup := r2.Group("/message")
{
messageCMSRouterGroup.GET("/get_chat_logs", messageCMS.GetChatLogs)
messageCMSRouterGroup.POST("/broadcast_message", messageCMS.BroadcastMessage)
messageCMSRouterGroup.POST("/mass_send_message", messageCMS.MassSendMassage)
messageCMSRouterGroup.POST("/withdraw_message", messageCMS.WithdrawMessage)
}
return baseRouter
}

@ -0,0 +1,222 @@
package statistics
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pb "Open_IM/pkg/proto/statistics"
"Open_IM/pkg/utils"
"context"
"strings"
"github.com/gin-gonic/gin"
)
func GetMessagesStatistics(c *gin.Context) {
var (
req cms_api_struct.GetMessageStatisticsRequest
resp cms_api_struct.GetMessageStatisticsResponse
reqPb pb.GetMessageStatisticsReq
)
reqPb.StatisticsReq = &pb.StatisticsReq{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetMessageStatistics(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, constant.ErrServer, resp)
log.NewError("0", utils.GetSelfFuncName(), err.Error())
return
}
// utils.CopyStructFields(&resp, respPb)
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:\"message_num\""
}{
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:\"message_num\""
}{
Date: v.Date,
MessageNum: int(v.Num),
})
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetUserStatistics(c *gin.Context) {
var (
req cms_api_struct.GetUserStatisticsRequest
resp cms_api_struct.GetUserStatisticsResponse
reqPb pb.GetUserStatisticsReq
)
reqPb.StatisticsReq = &pb.StatisticsReq{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", utils.GetSelfFuncName(), "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetUserStatistics(context.Background(), &reqPb)
if err != nil {
log.NewError("0", utils.GetSelfFuncName(), err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
// utils.CopyStructFields(&resp, respPb)
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:\"active_user_num\""
}{
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:\"increase_user_num\""
}{
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:\"total_user_num\""
}{
Date: v.Date,
TotalUserNum: int(v.Num),
})
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetGroupStatistics(c *gin.Context) {
var (
req cms_api_struct.GetGroupStatisticsRequest
resp cms_api_struct.GetGroupStatisticsResponse
reqPb pb.GetGroupStatisticsReq
)
reqPb.StatisticsReq = &pb.StatisticsReq{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.StatisticsReq, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetGroupStatistics(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
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:\"increase_group_num\""
}{
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:\"total_group_num\""
}{
Date: v.Date,
TotalGroupNum: int(v.Num),
})
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetActiveUser(c *gin.Context) {
var (
req cms_api_struct.GetActiveUserRequest
resp cms_api_struct.GetActiveUserResponse
reqPb pb.GetActiveUserReq
)
reqPb.StatisticsReq = &pb.StatisticsReq{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetActiveUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
utils.CopyStructFields(&resp.ActiveUserList, respPb.Users)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetActiveGroup(c *gin.Context) {
var (
req cms_api_struct.GetActiveGroupRequest
resp cms_api_struct.GetActiveGroupResponse
reqPb pb.GetActiveGroupReq
)
reqPb.StatisticsReq = &pb.StatisticsReq{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.StatisticsReq, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImStatisticsName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetActiveGroup(context.Background(), &reqPb)
if err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrServer, nil)
return
}
for _, group := range respPb.Groups {
resp.ActiveGroupList = append(resp.ActiveGroupList, struct {
GroupName string "json:\"group_name\""
GroupId string "json:\"group_id\""
MessageNum int "json:\"message_num\""
}{
GroupName: group.GroupName,
GroupId: group.GroupId,
MessageNum: int(group.MessageNum),
})
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}

@ -0,0 +1,308 @@
package user
import (
"Open_IM/pkg/cms_api_struct"
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
commonPb "Open_IM/pkg/proto/sdk_ws"
pb "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
func GetUserById(c *gin.Context) {
var (
req cms_api_struct.GetUserRequest
resp cms_api_struct.GetUserResponse
reqPb pb.GetUserByIdReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetUserById(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
if respPb.User.UserId == "" {
openIMHttp.RespHttp200(c, constant.OK, nil)
return
}
utils.CopyStructFields(&resp, respPb.User)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetUsersByName(c *gin.Context) {
var (
req cms_api_struct.GetUsersByNameRequest
resp cms_api_struct.GetUsersByNameResponse
reqPb pb.GetUsersByNameReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.UserName = req.UserName
reqPb.Pagination = &commonPb.RequestPagination{
PageNumber: int32(req.PageNumber),
ShowNumber: int32(req.ShowNumber),
}
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetUsersByName(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "rpc", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
utils.CopyStructFields(&resp.Users, respPb.Users)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetUsers(c *gin.Context) {
var (
req cms_api_struct.GetUsersRequest
resp cms_api_struct.GetUsersResponse
reqPb pb.GetUsersReq
)
reqPb.Pagination = &commonPb.RequestPagination{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb.Pagination, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetUsers(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, resp)
return
}
utils.CopyStructFields(&resp.Users, respPb.User)
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func ResignUser(c *gin.Context) {
var (
req cms_api_struct.ResignUserRequest
resp cms_api_struct.ResignUserResponse
reqPb pb.ResignUserReq
)
if err := c.ShouldBind(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"errCode": http.StatusBadRequest, "errMsg": err.Error()})
return
}
utils.CopyStructFields(&reqPb, &req)
fmt.Println(reqPb.UserId)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.ResignUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, resp)
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func AlterUser(c *gin.Context) {
var (
req cms_api_struct.AlterUserRequest
resp cms_api_struct.AlterUserResponse
reqPb pb.AlterUserReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.AlterUser(context.Background(), &reqPb)
if err != nil {
log.NewError("0", "microserver failed ", err.Error())
openIMHttp.RespHttp200(c, err, nil)
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func AddUser(c *gin.Context) {
var (
req cms_api_struct.AddUserRequest
reqPb pb.AddUserReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.AddUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}
func BlockUser(c *gin.Context) {
var (
req cms_api_struct.BlockUserRequest
resp cms_api_struct.BlockUserResponse
reqPb pb.BlockUserReq
)
if err := c.BindJSON(&req); err != nil {
fmt.Println(err)
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
utils.CopyStructFields(&reqPb, &req)
fmt.Println(reqPb, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
fmt.Println(reqPb)
_, err := client.BlockUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, resp)
return
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func UnblockUser(c *gin.Context) {
var (
req cms_api_struct.UnblockUserRequest
resp cms_api_struct.UnBlockUserResponse
reqPb pb.UnBlockUserReq
)
if err := c.ShouldBind(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
utils.CopyStructFields(&reqPb, &req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.UnBlockUser(context.Background(), &reqPb)
if err != nil {
openIMHttp.RespHttp200(c, err, resp)
return
}
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetBlockUsers(c *gin.Context) {
var (
req cms_api_struct.GetBlockUsersRequest
resp cms_api_struct.GetBlockUsersResponse
reqPb pb.GetBlockUsersReq
respPb *pb.GetBlockUsersResp
)
reqPb.Pagination = &commonPb.RequestPagination{}
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "ShouldBindQuery failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, resp)
return
}
utils.CopyStructFields(&reqPb.Pagination, &req)
log.NewInfo(reqPb.OperationID, utils.GetSelfFuncName(), "blockUsers", reqPb.Pagination, req)
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetBlockUsers(context.Background(), &reqPb)
if err != nil {
log.NewError(reqPb.OperationID, utils.GetSelfFuncName(), "GetBlockUsers rpc", err.Error())
openIMHttp.RespHttp200(c, err, resp)
return
}
for _, v := range respPb.BlockUsers {
resp.BlockUsers = append(resp.BlockUsers, cms_api_struct.BlockUser{
UserResponse: cms_api_struct.UserResponse{
UserId: v.User.UserId,
ProfilePhoto: v.User.ProfilePhoto,
Nickname: v.User.Nickname,
IsBlock: v.User.IsBlock,
CreateTime: v.User.CreateTime,
},
BeginDisableTime: v.BeginDisableTime,
EndDisableTime: v.EndDisableTime,
})
}
resp.ShowNumber = int(respPb.Pagination.ShowNumber)
resp.CurrentPage = int(respPb.Pagination.CurrentPage)
resp.UserNums = respPb.UserNums
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func GetBlockUserById(c *gin.Context) {
var (
req cms_api_struct.GetBlockUserRequest
resp cms_api_struct.GetBlockUserResponse
reqPb pb.GetBlockUserByIdReq
)
if err := c.ShouldBindQuery(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.UserId = req.UserId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
respPb, err := client.GetBlockUserById(context.Background(), &reqPb)
if err != nil {
log.NewError("0", "GetBlockUserById rpc failed ", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
resp.EndDisableTime = respPb.BlockUser.EndDisableTime
resp.BeginDisableTime = respPb.BlockUser.BeginDisableTime
utils.CopyStructFields(&resp, respPb.BlockUser.User)
openIMHttp.RespHttp200(c, constant.OK, resp)
}
func DeleteUser(c *gin.Context) {
var (
req cms_api_struct.DeleteUserRequest
reqPb pb.DeleteUserReq
)
if err := c.BindJSON(&req); err != nil {
log.NewError("0", "BindJSON failed ", err.Error())
openIMHttp.RespHttp200(c, constant.ErrArgs, nil)
return
}
reqPb.UserId = req.UserId
etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImUserName)
client := pb.NewUserClient(etcdConn)
_, err := client.DeleteUser(context.Background(), &reqPb)
if err != nil {
log.NewError("0", "DeleteUser rpc failed ", err.Error())
openIMHttp.RespHttp200(c, err, nil)
return
}
openIMHttp.RespHttp200(c, constant.OK, nil)
}

@ -121,12 +121,12 @@ func MsgToUser(pushMsg *pbPush.PushMsgReq) {
// case constant.GroupChatType:
// etcdConn := getcdv3.GetConn(config.Config.Etcd.EtcdSchema, strings.Join(config.Config.Etcd.EtcdAddr, ","), config.Config.RpcRegisterName.OpenImGroupName)
// client := pbGroup.NewGroupClient(etcdConn)
// req := &pbGroup.GetGroupAllMemberReq{
// req := &pbGroup.Req{
// GroupID: m.RecvID,
// Token: config.Config.Secret,
// OperationID: m.OperationID,
// }
// reply, err := client.GetGroupAllMember(context.Background(), req)
// reply, err := client.(context.Background(), req)
// if err != nil {
// log.Error(m.Token, m.OperationID, "rpc getGroupInfo failed, err = %s", err.Error())
// return

@ -0,0 +1,91 @@
package admin_cms
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
openIMHttp "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbAdminCMS "Open_IM/pkg/proto/admin_cms"
"Open_IM/pkg/utils"
"context"
"google.golang.org/grpc"
"net"
"strconv"
"strings"
)
type adminCMSServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewAdminCMSServer(port int) *adminCMSServer {
log.NewPrivateLog("AdminCMS")
return &adminCMSServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImAdminCMSName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *adminCMSServer) Run() {
log.NewInfo("0", "AdminCMS rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbAdminCMS.RegisterAdminCMSServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
}
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(_ context.Context, req *pbAdminCMS.AdminLoginReq) (*pbAdminCMS.AdminLoginResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbAdminCMS.AdminLoginResp{}
for _, adminID := range config.Config.Manager.AppManagerUid{
if adminID == req.AdminID {
for _, secret := range config.Config.Manager.Secrets {
if secret == req.Secret {
token, expTime, err := token_verify.CreateToken(adminID,9843)
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "generate token success", "token: ", token, "expTime:", expTime)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "generate token failed", "adminID: ", adminID, err.Error())
return resp, openIMHttp.WrapError(constant.ErrTokenUnknown)
}
resp.Token = token
break
}
}
}
}
if resp.Token == "" {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "failed")
return resp, openIMHttp.WrapError(constant.ErrTokenMalformed)
}
return resp, nil
}

@ -6,6 +6,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
cp "Open_IM/pkg/common/utils"
@ -14,11 +15,12 @@ import (
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"google.golang.org/grpc"
"net"
"strconv"
"strings"
"time"
"google.golang.org/grpc"
)
type groupServer struct {
@ -582,7 +584,7 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
group, err := imdb.GetGroupInfoByGroupID(req.GroupInfo.GroupID)
if err != nil {
log.NewError(req.OperationID, "GetGroupInfoByGroupID failed ", err.Error(), req.GroupInfo.GroupID)
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, nil
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrAccess.ErrMsg}}, http.WrapError(constant.ErrDB)
}
////bitwise operators: 0001:groupName; 0010:Notification 0100:Introduction; 1000:FaceUrl; 10000:owner
@ -605,7 +607,7 @@ func (s *groupServer) SetGroupInfo(ctx context.Context, req *pbGroup.SetGroupInf
err = imdb.SetGroupInfo(groupInfo)
if err != nil {
log.NewError(req.OperationID, "SetGroupInfo failed ", err.Error(), groupInfo)
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, nil
return &pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{ErrCode: constant.ErrDB.ErrCode, ErrMsg: constant.ErrDB.ErrMsg}}, http.WrapError(constant.ErrDB)
}
log.NewInfo(req.OperationID, "SetGroupInfo rpc return ", pbGroup.SetGroupInfoResp{CommonResp: &pbGroup.CommonResp{}})
if changedType != 0 {
@ -639,6 +641,237 @@ func (s *groupServer) TransferGroupOwner(_ context.Context, req *pbGroup.Transfe
}
func (s *groupServer) GetGroupById(_ context.Context, req *pbGroup.GetGroupByIdReq) (*pbGroup.GetGroupByIdResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbGroup.GetGroupByIdResp{CMSGroup: &pbGroup.CMSGroup{
GroupInfo: &open_im_sdk.GroupInfo{},
}}
group, err := imdb.GetGroupById(req.GroupId)
if err != nil {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetGroupById error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
resp.CMSGroup.GroupInfo = &open_im_sdk.GroupInfo{
GroupID: group.GroupID,
GroupName: group.GroupName,
FaceURL: group.FaceURL,
OwnerUserID: group.CreatorUserID,
MemberCount: 0,
Status: group.Status,
CreatorUserID: group.CreatorUserID,
GroupType: group.GroupType,
}
groupMember, err := imdb.GetGroupMaster(group.GroupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMaster", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
resp.CMSGroup.GroupMasterName = groupMember.Nickname
resp.CMSGroup.GroupMasterId = groupMember.UserID
resp.CMSGroup.GroupInfo.CreatorUserID = group.CreatorUserID
return resp, nil
}
func (s *groupServer) GetGroup(_ context.Context, req *pbGroup.GetGroupReq) (*pbGroup.GetGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbGroup.GetGroupResp{
CMSGroups: []*pbGroup.CMSGroup{},
}
groups, err := imdb.GetGroupsByName(req.GroupName, req.Pagination.PageNumber, req.Pagination.ShowNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupsByName error", req.String())
return resp, http.WrapError(constant.ErrDB)
}
nums, err := imdb.GetGroupsCountNum(db.Group{GroupName:req.GroupName})
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupsCountNum error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
resp.GroupNums = nums
resp.Pagination = &open_im_sdk.RequestPagination{
PageNumber: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
for _, v := range groups {
groupMember, err := imdb.GetGroupMaster(v.GroupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMaster error", err.Error())
continue
}
resp.CMSGroups = append(resp.CMSGroups, &pbGroup.CMSGroup{
GroupInfo: &open_im_sdk.GroupInfo{
GroupID: v.GroupID,
GroupName: v.GroupName,
FaceURL: v.FaceURL,
OwnerUserID: v.CreatorUserID,
Status: v.Status,
CreatorUserID: v.CreatorUserID,
},
GroupMasterName: groupMember.Nickname,
GroupMasterId: groupMember.UserID,
})
}
return resp, nil
}
func (s *groupServer) GetGroups(_ context.Context, req *pbGroup.GetGroupsReq) (*pbGroup.GetGroupsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetGroups ", req.String())
resp := &pbGroup.GetGroupsResp{
CMSGroups: []*pbGroup.CMSGroup{},
Pagination: &open_im_sdk.RequestPagination{},
}
groups, err := imdb.GetGroups(int(req.Pagination.PageNumber), int(req.Pagination.ShowNumber))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroups error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
groupsCountNum, err := imdb.GetGroupsCountNum(db.Group{})
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "groupsCountNum ", groupsCountNum)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupsCountNum", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
resp.GroupNum = int32(groupsCountNum)
resp.Pagination.PageNumber = req.Pagination.PageNumber
resp.Pagination.ShowNumber = req.Pagination.ShowNumber
for _, v := range groups {
groupMember, err := imdb.GetGroupMaster(v.GroupID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
continue
}
resp.CMSGroups = append(resp.CMSGroups, &pbGroup.CMSGroup{
GroupInfo: &open_im_sdk.GroupInfo{
GroupID: v.GroupID,
GroupName: v.GroupName,
FaceURL: v.FaceURL,
OwnerUserID: v.CreatorUserID,
Status: v.Status,
CreatorUserID: v.CreatorUserID,
},
GroupMasterId: groupMember.UserID,
GroupMasterName: groupMember.Nickname,
})
}
return resp, nil
}
func (s *groupServer) OperateGroupStatus(_ context.Context, req *pbGroup.OperateGroupStatusReq) (*pbGroup.OperateGroupStatusResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbGroup.OperateGroupStatusResp{}
if err := imdb.OperateGroupStatus(req.GroupId, req.Status); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "OperateGroupStatus", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *groupServer) DeleteGroup(_ context.Context, req *pbGroup.DeleteGroupReq) (*pbGroup.DeleteGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbGroup.DeleteGroupResp{}
if err := imdb.DeleteGroup(req.GroupId); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "DeleteGroup error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *groupServer) OperateUserRole(_ context.Context, req *pbGroup.OperateUserRoleReq) (*pbGroup.OperateUserRoleResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "args:", req.String())
resp := &pbGroup.OperateUserRoleResp{}
if err := imdb.OperateGroupRole(req.UserId, req.GroupId, req.RoleLevel); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "OperateGroupRole error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *groupServer) GetGroupMembersCMS(_ context.Context, req *pbGroup.GetGroupMembersCMSReq) (*pbGroup.GetGroupMembersCMSResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "args:", req.String())
resp := &pbGroup.GetGroupMembersCMSResp{}
groupMembers, err := imdb.GetGroupMembersByGroupIdCMS(req.GroupId, req.UserName, req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(),"GetGroupMembersByGroupIdCMS Error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
groupMembersCount, err := imdb.GetGroupMembersCount(req.GroupId, req.UserName)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupMembersCMS Error", err.Error())
return resp, http.WrapError(constant.ErrDB)
}
log.NewInfo(req.OperationID, groupMembersCount)
resp.MemberNums = groupMembersCount
for _, groupMember := range groupMembers {
resp.Members = append(resp.Members, &open_im_sdk.GroupMemberFullInfo{
GroupID: req.GroupId,
UserID: groupMember.UserID,
RoleLevel: groupMember.RoleLevel,
JoinTime: groupMember.JoinTime.Unix(),
Nickname: groupMember.Nickname,
FaceURL: groupMember.FaceURL,
JoinSource: groupMember.JoinSource,
})
}
resp.Pagination = &open_im_sdk.ResponsePagination{
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
return resp, nil
}
func (s *groupServer) RemoveGroupMembersCMS(_ context.Context, req *pbGroup.RemoveGroupMembersCMSReq) (*pbGroup.RemoveGroupMembersCMSResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "args:", req.String())
resp := &pbGroup.RemoveGroupMembersCMSResp{}
for _, userId := range req.UserIds {
err := imdb.RemoveGroupMember(req.GroupId, userId)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
resp.Failed = append(resp.Failed, userId)
} else {
resp.Success = append(resp.Success, userId)
}
}
return resp, nil
}
func (s *groupServer) AddGroupMembersCMS(_ context.Context, req *pbGroup.AddGroupMembersCMSReq) (*pbGroup.AddGroupMembersCMSResp, error) {
log.NewInfo(req.OperationId, utils.GetSelfFuncName(), "args:", req.String())
resp := &pbGroup.AddGroupMembersCMSResp{}
for _, userId := range req.UserIds {
if isExist := imdb.IsExistGroupMember(req.GroupId, userId); isExist {
log.NewError(req.OperationId, utils.GetSelfFuncName(), "user is exist in group", userId, req.GroupId)
resp.Failed = append(resp.Failed, userId)
continue
}
user, err := imdb.GetUserByUserID(userId)
if err != nil {
log.NewError(req.OperationId, utils.GetSelfFuncName(), "GetUserByUserID", err.Error())
resp.Failed = append(resp.Failed, userId)
continue
}
groupMember := db.GroupMember{
GroupID: req.GroupId,
UserID: userId,
Nickname: user.Nickname,
FaceURL: "",
RoleLevel: 1,
JoinTime: time.Time{},
JoinSource: constant.JoinByAdmin,
OperatorUserID: "CmsAdmin",
Ex: "",
}
if err := imdb.InsertIntoGroupMember(groupMember); err != nil {
log.NewError(req.OperationId, utils.GetSelfFuncName(), "InsertIntoGroupMember failed", req.String())
resp.Failed = append(resp.Failed, userId)
} else {
resp.Success = append(resp.Success, userId)
}
}
return resp, nil
}
func (s *groupServer) GetUserReqApplicationList(_ context.Context, req *pbGroup.GetUserReqApplicationListReq) (*pbGroup.GetUserReqApplicationListResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbGroup.GetUserReqApplicationListResp{}
@ -675,4 +908,4 @@ func (s *groupServer) GetUserReqApplicationList(_ context.Context, req *pbGroup.
ErrMsg: "",
}
return resp, nil
}
}

@ -0,0 +1,143 @@
package messageCMS
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
errors "Open_IM/pkg/common/http"
"context"
"Open_IM/pkg/common/log"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbMessageCMS "Open_IM/pkg/proto/message_cms"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
)
type messageCMSServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewMessageCMSServer(port int) *messageCMSServer {
log.NewPrivateLog("MessageCMS")
return &messageCMSServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImMessageCMSName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *messageCMSServer) Run() {
log.NewInfo("0", "messageCMS rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbMessageCMS.RegisterMessageCMSServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
}
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "message cms rpc success")
}
func (s *messageCMSServer) BoradcastMessage(_ context.Context, req *pbMessageCMS.BoradcastMessageReq) (*pbMessageCMS.BoradcastMessageResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "BoradcastMessage", req.String())
resp := &pbMessageCMS.BoradcastMessageResp{}
return resp, errors.WrapError(constant.ErrDB)
}
func (s *messageCMSServer) GetChatLogs(_ context.Context, req *pbMessageCMS.GetChatLogsReq) (*pbMessageCMS.GetChatLogsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetChatLogs", req.String())
resp := &pbMessageCMS.GetChatLogsResp{}
time, err := utils.TimeStringToTime(req.Date)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "time string parse error", err.Error())
}
chatLog := db.ChatLog{
Content: req.Content,
SendTime: time,
}
chatLogs, err := imdb.GetChatLog(chatLog, req.Pagination.PageNumber, req.Pagination.ShowNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetChatLog", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
for _, chatLog := range chatLogs {
pbChatLog := &pbMessageCMS.ChatLogs{
SessionType: chatLog.SessionType,
ContentType: chatLog.ContentType,
SenderNickName: chatLog.SenderNickname,
SenderId: chatLog.SendID,
SearchContent: req.Content,
WholeContent: chatLog.Content,
Date: chatLog.CreateTime.String(),
}
switch chatLog.SessionType {
case constant.SingleChatType:
recvUser, err := imdb.GetUserByUserID(chatLog.RecvID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserByUserID failed", err.Error())
continue
}
pbChatLog.ReciverId = recvUser.UserID
pbChatLog.ReciverNickName = recvUser.Nickname
case constant.GroupChatType:
group, err := imdb.GetGroupById(chatLog.RecvID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetGroupById failed")
continue
}
pbChatLog.GroupId = group.GroupID
pbChatLog.GroupName = group.GroupName
}
resp.ChatLogs = append(resp.ChatLogs, pbChatLog)
}
resp.Pagination = &open_im_sdk.ResponsePagination{
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "resp output: ", resp.String())
return resp, nil
}
func (s *messageCMSServer) MassSendMessage(_ context.Context, req *pbMessageCMS.MassSendMessageReq) (*pbMessageCMS.MassSendMessageResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "MassSendMessage", req.String())
resp := &pbMessageCMS.MassSendMessageResp{}
return resp, nil
}
func (s *messageCMSServer) WithdrawMessage(_ context.Context, req *pbMessageCMS.WithdrawMessageReq) (*pbMessageCMS.WithdrawMessageResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "WithdrawMessage", req.String())
resp := &pbMessageCMS.WithdrawMessageResp{}
return resp, nil
}

@ -0,0 +1,361 @@
package statistics
import (
"Open_IM/pkg/common/config"
"context"
"sync"
"time"
//"Open_IM/pkg/common/constant"
//"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/log"
//cp "Open_IM/pkg/common/utils"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
pbStatistics "Open_IM/pkg/proto/statistics"
//open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
//"context"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
)
type statisticsServer struct {
rpcPort int
rpcRegisterName string
etcdSchema string
etcdAddr []string
}
func NewStatisticsServer(port int) *statisticsServer {
log.NewPrivateLog("Statistics")
return &statisticsServer{
rpcPort: port,
rpcRegisterName: config.Config.RpcRegisterName.OpenImStatisticsName,
etcdSchema: config.Config.Etcd.EtcdSchema,
etcdAddr: config.Config.Etcd.EtcdAddr,
}
}
func (s *statisticsServer) Run() {
log.NewInfo("0", "Statistics rpc start ")
ip := utils.ServerIP
registerAddress := ip + ":" + strconv.Itoa(s.rpcPort)
//listener network
listener, err := net.Listen("tcp", registerAddress)
if err != nil {
log.NewError("0", "Listen failed ", err.Error(), registerAddress)
return
}
log.NewInfo("0", "listen network success, ", registerAddress, listener)
defer listener.Close()
//grpc server
srv := grpc.NewServer()
defer srv.GracefulStop()
//Service registers with etcd
pbStatistics.RegisterUserServer(srv, s)
err = getcdv3.RegisterEtcd(s.etcdSchema, strings.Join(s.etcdAddr, ","), ip, s.rpcPort, s.rpcRegisterName, 10)
if err != nil {
log.NewError("0", "RegisterEtcd failed ", err.Error())
return
}
err = srv.Serve(listener)
if err != nil {
log.NewError("0", "Serve failed ", err.Error())
return
}
log.NewInfo("0", "statistics rpc success")
}
func (s *statisticsServer) GetActiveGroup(_ context.Context, req *pbStatistics.GetActiveGroupReq) (*pbStatistics.GetActiveGroupResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetActiveGroupResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
activeGroups, err := imdb.GetActiveGroups(fromTime, toTime, 12)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
for _, activeGroup := range activeGroups {
resp.Groups = append(resp.Groups,
&pbStatistics.GroupResp{
GroupName: activeGroup.Name,
GroupId: activeGroup.Id,
MessageNum: int32(activeGroup.MessageNum),
})
}
return resp, nil
}
func (s *statisticsServer) GetActiveUser(_ context.Context, req *pbStatistics.GetActiveUserReq) (*pbStatistics.GetActiveUserResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetActiveUserResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
activeUsers, err := imdb.GetActiveUsers(fromTime, toTime, 12)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
for _, activeUser := range activeUsers {
resp.Users = append(resp.Users,
&pbStatistics.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):
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 *statisticsServer) GetGroupStatistics(_ context.Context, req *pbStatistics.GetGroupStatisticsReq) (*pbStatistics.GetGroupStatisticsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetGroupStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
increaseGroupNum, err := imdb.GetIncreaseGroupNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
totalGroupNum, err := imdb.GetTotalGroupNum()
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
resp.IncreaseGroupNum = increaseGroupNum
resp.TotalGroupNum = totalGroupNum
times := GetRangeDate(fromTime, toTime)
log.NewInfo(req.OperationID, "times:", times)
wg := &sync.WaitGroup{}
resp.IncreaseGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.TotalGroupNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
log.NewInfo(req.OperationID, resp.TotalGroupNumList, resp.TotalGroupNumList)
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 := imdb.GetIncreaseGroupNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.IncreaseGroupNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
num, err = imdb.GetGroupNum(v[0])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.TotalGroupNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}
func (s *statisticsServer) GetMessageStatistics(_ context.Context, req *pbStatistics.GetMessageStatisticsReq) (*pbStatistics.GetMessageStatisticsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetMessageStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
privateMessageNum, err := imdb.GetPrivateMessageNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
return resp, err
}
groupMessageNum, err := imdb.GetGroupMessageNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
}
resp.PrivateMessageNum = privateMessageNum
resp.GroupMessageNum = groupMessageNum
times := GetRangeDate(fromTime, toTime)
resp.GroupMessageNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.PrivateMessageNumList = make([]*pbStatistics.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 := imdb.GetPrivateMessageNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.PrivateMessageNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
num, err = imdb.GetGroupMessageNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.GroupMessageNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}
func (s *statisticsServer) GetUserStatistics(_ context.Context, req *pbStatistics.GetUserStatisticsReq) (*pbStatistics.GetUserStatisticsResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbStatistics.GetUserStatisticsResp{}
fromTime, toTime, err := ParseTimeFromTo(req.StatisticsReq.From, req.StatisticsReq.To)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "ParseTimeFromTo", err.Error())
return resp, err
}
activeUserNum, err := imdb.GetActiveUserNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetActiveUserNum", err.Error())
return resp, err
}
increaseUserNum, err := imdb.GetIncreaseUserNum(fromTime, toTime.Add(time.Hour*24))
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseUserNum error", err.Error())
return resp, err
}
totalUserNum, err := imdb.GetTotalUserNum()
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTotalUserNum error", err.Error())
return resp, err
}
resp.ActiveUserNum = activeUserNum
resp.TotalUserNum = totalUserNum
resp.IncreaseUserNum = increaseUserNum
times := GetRangeDate(fromTime, toTime)
resp.TotalUserNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.ActiveUserNumList = make([]*pbStatistics.DateNumList, len(times), len(times))
resp.IncreaseUserNumList = make([]*pbStatistics.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 := imdb.GetActiveUserNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseGroupNum", v, err.Error())
}
resp.ActiveUserNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
num, err = imdb.GetTotalUserNumByDate(v[0])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetTotalUserNumByDate", v, err.Error())
}
resp.TotalUserNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
num, err = imdb.GetIncreaseUserNum(v[0], v[1])
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetIncreaseUserNum", v, err.Error())
}
resp.IncreaseUserNumList[index] = &pbStatistics.DateNumList{
Date: v[0].String(),
Num: num,
}
}(wg, i, v)
}
wg.Wait()
return resp, nil
}

@ -6,6 +6,8 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
errors "Open_IM/pkg/common/http"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/token_verify"
"Open_IM/pkg/grpc-etcdv3/getcdv3"
@ -14,10 +16,12 @@ import (
pbUser "Open_IM/pkg/proto/user"
"Open_IM/pkg/utils"
"context"
"google.golang.org/grpc"
"fmt"
"net"
"strconv"
"strings"
"google.golang.org/grpc"
)
type userServer struct {
@ -243,3 +247,211 @@ func (s *userServer) UpdateUserInfo(ctx context.Context, req *pbUser.UpdateUserI
log.Info(req.OperationID, "UserInfoUpdatedNotification ", req.UserInfo.UserID, req.OpUserID)
return &pbUser.UpdateUserInfoResp{CommonResp: &pbUser.CommonResp{}}, nil
}
func (s *userServer) GetUsersByName(ctx context.Context, req *pbUser.GetUsersByNameReq) (*pbUser.GetUsersByNameResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String())
resp := &pbUser.GetUsersByNameResp{}
users, err := imdb.GetUserByName(req.UserName, req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUserByName failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
for _, user := range users {
isBlock, err := imdb.UserIsBlock(user.UserID)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), err.Error())
continue
}
resp.Users = append(resp.Users, &pbUser.User{
ProfilePhoto: user.FaceURL,
Nickname: user.Nickname,
UserId: user.UserID,
CreateTime: user.CreateTime.String(),
IsBlock: isBlock,
})
}
user := db.User{Nickname: req.UserName}
userNums, err := imdb.GetUsersCount(user)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
resp.UserNums = userNums
resp.Pagination = &sdkws.ResponsePagination{
CurrentPage: req.Pagination.PageNumber,
ShowNumber: req.Pagination.ShowNumber,
}
return resp, nil
}
func (s *userServer) GetUserById(ctx context.Context, req *pbUser.GetUserByIdReq) (*pbUser.GetUserByIdResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req:", req.String())
resp := &pbUser.GetUserByIdResp{User: &pbUser.User{}}
user, err := imdb.GetUserByUserID(req.UserId)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
return resp, errors.WrapError(constant.ErrDB)
}
isBlock, err := imdb.UserIsBlock(req.UserId)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "req", req.String())
return resp, errors.WrapError(constant.ErrDB)
}
resp.User = &pbUser.User{
ProfilePhoto: user.FaceURL,
Nickname: user.Nickname,
UserId: user.UserID,
CreateTime: user.CreateTime.String(),
IsBlock: isBlock,
}
return resp, nil
}
func (s *userServer) GetUsers(ctx context.Context, req *pbUser.GetUsersReq) (*pbUser.GetUsersResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "req: ", req.String())
resp := &pbUser.GetUsersResp{User: []*pbUser.User{}}
users, err := imdb.GetUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
return resp, errors.WrapError(constant.ErrDB)
}
for _, v := range users {
isBlock, err := imdb.UserIsBlock(v.UserID)
if err == nil {
user := &pbUser.User{
ProfilePhoto: v.FaceURL,
UserId: v.UserID,
CreateTime: v.CreateTime.String(),
Nickname: v.Nickname,
IsBlock: isBlock,
}
resp.User = append(resp.User, user)
}
}
user := db.User{}
nums, err := imdb.GetUsersCount(user)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetUsersCount failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
resp.UserNums = nums
resp.Pagination = &sdkws.ResponsePagination{ShowNumber: req.Pagination.ShowNumber, CurrentPage: req.Pagination.PageNumber}
return resp, nil
}
func (s *userServer) ResignUser(ctx context.Context, req *pbUser.ResignUserReq) (*pbUser.ResignUserResp, error) {
log.NewInfo(req.OperationID, "ResignUser args ", req.String())
return &pbUser.ResignUserResp{}, nil
}
func (s *userServer) AlterUser(ctx context.Context, req *pbUser.AlterUserReq) (*pbUser.AlterUserResp, error) {
log.NewInfo(req.OperationID, "AlterUser args ", req.String())
resp := &pbUser.AlterUserResp{}
user := db.User{
PhoneNumber: strconv.FormatInt(req.PhoneNumber, 10),
Nickname: req.Nickname,
Email: req.Email,
UserID: req.UserId,
}
if err := imdb.UpdateUserInfo(user); err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "UpdateUserInfo", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *userServer) AddUser(ctx context.Context, req *pbUser.AddUserReq) (*pbUser.AddUserResp, error) {
log.NewInfo(req.OperationID, "AddUser args ", req.String())
resp := &pbUser.AddUserResp{}
err := imdb.AddUser(req.UserId, req.PhoneNumber, req.Name)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "AddUser", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *userServer) BlockUser(ctx context.Context, req *pbUser.BlockUserReq) (*pbUser.BlockUserResp, error) {
log.NewInfo(req.OperationID, "BlockUser args ", req.String())
fmt.Println("BlockUser args ", req.String())
resp := &pbUser.BlockUserResp{}
err := imdb.BlockUser(req.UserId, req.EndDisableTime)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "BlockUser", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *userServer) UnBlockUser(ctx context.Context, req *pbUser.UnBlockUserReq) (*pbUser.UnBlockUserResp, error) {
log.NewInfo(req.OperationID, "UnBlockUser args ", req.String())
resp := &pbUser.UnBlockUserResp{}
err := imdb.UnBlockUser(req.UserId)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "unBlockUser", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
return resp, nil
}
func (s *userServer) GetBlockUsers(ctx context.Context, req *pbUser.GetBlockUsersReq) (*pbUser.GetBlockUsersResp, error) {
log.NewInfo(req.OperationID, "GetBlockUsers args ", req.String())
resp := &pbUser.GetBlockUsersResp{}
blockUsers, err := imdb.GetBlockUsers(req.Pagination.ShowNumber, req.Pagination.PageNumber)
if err != nil {
log.Error(req.OperationID, utils.GetSelfFuncName(), "GetBlockUsers", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
for _, v := range blockUsers {
resp.BlockUsers = append(resp.BlockUsers, &pbUser.BlockUser{
User: &pbUser.User{
ProfilePhoto: v.User.FaceURL,
Nickname: v.User.Nickname,
UserId: v.User.UserID,
IsBlock: true,
},
BeginDisableTime: (v.BeginDisableTime).String(),
EndDisableTime: (v.EndDisableTime).String(),
})
}
resp.Pagination = &sdkws.ResponsePagination{}
resp.Pagination.ShowNumber = req.Pagination.ShowNumber
resp.Pagination.CurrentPage = req.Pagination.PageNumber
nums, err := imdb.GetBlockUsersNumCount()
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetBlockUsersNumCount failed", err.Error())
return resp, errors.WrapError(constant.ErrDB)
}
resp.UserNums = nums
return resp, nil
}
func (s *userServer) GetBlockUserById(_ context.Context, req *pbUser.GetBlockUserByIdReq) (*pbUser.GetBlockUserByIdResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), "GetBlockUserById args ", req.String())
resp := &pbUser.GetBlockUserByIdResp{}
user, err := imdb.GetBlockUserById(req.UserId)
if err != nil {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "GetBlockUserById", err)
return resp, errors.WrapError(constant.ErrDB)
}
resp.BlockUser = &pbUser.BlockUser{
User: &pbUser.User{
ProfilePhoto: user.User.FaceURL,
Nickname: user.User.Nickname,
UserId: user.User.UserID,
IsBlock: true,
},
BeginDisableTime: (user.BeginDisableTime).String(),
EndDisableTime: (user.EndDisableTime).String(),
}
return resp, nil
}
func (s *userServer) DeleteUser(_ context.Context, req *pbUser.DeleteUserReq) (*pbUser.DeleteUserResp, error) {
log.NewInfo(req.OperationID, utils.GetSelfFuncName(), req.String())
resp := &pbUser.DeleteUserResp{}
if row := imdb.DeleteUser(req.UserId); row == 0 {
log.NewError(req.OperationID, utils.GetSelfFuncName(), "delete failed", "delete rows:", row)
return resp, errors.WrapError(constant.ErrDB)
}
return resp, nil
}

@ -0,0 +1,10 @@
package cms_api_struct
type AdminLoginRequest struct {
AdminName string `json:"admin_name" binding:"required"`
Secret string `json:"secret" binding:"required"`
}
type AdminLoginResponse struct {
Token string `json:"token"`
}

@ -0,0 +1,11 @@
package cms_api_struct
type RequestPagination struct {
PageNumber int `form:"page_number" binding:"required"`
ShowNumber int `form:"show_number" binding:"required"`
}
type ResponsePagination struct {
CurrentPage int `json:"current_number" binding:"required"`
ShowNumber int `json:"show_number" binding:"required"`
}

@ -0,0 +1,146 @@
package cms_api_struct
type GroupResponse struct {
GroupName string `json:"group_name"`
GroupID string `json:"group_id"`
GroupMasterName string `json:"group_master_name"`
GroupMasterId string `json:"group_master_id"`
CreateTime string `json:"create_time"`
IsBanChat bool `json:"is_ban_chat"`
IsBanPrivateChat bool `json:"is_ban_private_chat"`
ProfilePhoto string `json:"profile_photo"`
}
type GetGroupByIdRequest struct {
GroupId string `form:"group_id" binding:"required"`
}
type GetGroupByIdResponse struct {
GroupResponse
}
type GetGroupRequest struct {
GroupName string `form:"group_name" binding:"required"`
RequestPagination
}
type GetGroupResponse struct {
Groups []GroupResponse `json:"groups"`
GroupNums int `json:"group_nums"`
ResponsePagination
}
type GetGroupsRequest struct {
RequestPagination
}
type GetGroupsResponse struct {
Groups []GroupResponse `json:"groups"`
GroupNums int `json:"group_nums"`
ResponsePagination
}
type CreateGroupRequest struct {
GroupName string `json:"group_name" binding:"required"`
GroupMasterId string `json:"group_master_id" binding:"required"`
GroupMembers []string `json:"group_members" binding:"required"`
}
type CreateGroupResponse struct {
}
type SetGroupMasterRequest struct {
GroupId string `json:"group_id" binding:"required"`
UserId string `json:"user_id" binding:"required"`
}
type SetGroupMasterResponse struct {
}
type SetGroupMemberRequest struct {
GroupId string `json:"group_id" binding:"required"`
UserId string `json:"user_id" binding:"required"`
}
type SetGroupMemberRespones struct {
}
type BanGroupChatRequest struct {
GroupId string `json:"group_id" binding:"required"`
}
type BanGroupChatResponse struct {
}
type BanPrivateChatRequest struct {
GroupId string `json:"group_id" binding:"required"`
}
type BanPrivateChatResponse struct {
}
type DeleteGroupRequest struct {
GroupId string `json:"group_id" binding:"required"`
}
type DeleteGroupResponse struct {
}
type GetGroupMembersRequest struct {
GroupId string `form:"group_id" binding:"required"`
UserName string `form:"user_name"`
RequestPagination
}
type GroupMemberResponse struct {
MemberPosition int `json:"member_position"`
MemberNickName string `json:"member_nick_name"`
MemberId string `json:"member_id"`
JoinTime string `json:"join_time"`
}
type GetGroupMembersResponse struct {
GroupMembers []GroupMemberResponse `json:"group_members"`
ResponsePagination
MemberNums int `json:"member_nums"`
}
type GroupMemberRequest struct {
GroupId string `json:"group_id" binding:"required"`
Members []string `json:"members" binding:"required"`
}
type GroupMemberOperateResponse struct {
Success []string `json:"success"`
Failed []string `json:"failed"`
}
type AddGroupMembersRequest struct {
GroupMemberRequest
}
type AddGroupMembersResponse struct {
GroupMemberOperateResponse
}
type RemoveGroupMembersRequest struct {
GroupMemberRequest
}
type RemoveGroupMembersResponse struct{
GroupMemberOperateResponse
}
type AlterGroupInfoRequest struct {
GroupID string `json:"group_id"`
GroupName string `json:"group_name"`
Notification string `json:"notification"`
Introduction string `json:"introduction"`
ProfilePhoto string `json:"profile_photo"`
GroupType int `json:"group_type"`
}
type AlterGroupInfoResponse struct {
}

@ -0,0 +1,48 @@
package cms_api_struct
type BroadcastRequest struct {
Message string `json:"message"`
}
type BroadcastResponse struct {
}
type MassSendMassageRequest struct {
}
type MassSendMassageResponse struct {
}
type GetChatLogsRequest struct {
SessionType int `form:"session_type"`
ContentType int `form:"content_type"`
Content string `form:"content"`
UserId string `form:"user_id"`
GroupId string `form:"group_id"`
Date string `form:"date"`
RequestPagination
}
type ChatLog struct {
SessionType int `json:"session_type"`
ContentType int `json:"content_type"`
SenderNickName string `json:"sender_nick_name"`
SenderId int `json:"sender_id"`
SearchContent string `json:"search_content"`
WholeContent string `json:"whole_content"`
ReceiverNickName string `json:"receiver_nick_name"`
ReceiverID int `json:"receiver_id"`
GroupName string `json:"group_name"`
GroupId string `json:"group_id"`
Date string `json:"date"`
}
type GetChatLogsResponse struct {
ChatLogs []ChatLog `json:"chat_logs"`
logNums int `json:"log_nums"`
ResponsePagination
}

@ -0,0 +1,25 @@
package cms_api_struct
type GetStaffsResponse struct {
StaffsList []struct {
ProfilePhoto string `json:"profile_photo"`
NickName string `json:"nick_name"`
StaffId int `json:"staff_id"`
Position string `json:"position"`
EntryTime string `json:"entry_time"`
} `json:"staffs_list"`
}
type GetOrganizationsResponse struct {
OrganizationList []struct {
OrganizationId int `json:"organization_id"`
OrganizationName string `json:"organization_name"`
} `json:"organization_list"`
}
type SquadResponse struct {
SquadList []struct {
SquadId int `json:"squad_id"`
SquadName string `json:"squad_name"`
} `json:"squad_list"`
}

@ -0,0 +1,89 @@
package cms_api_struct
type GetStatisticsRequest struct {
From string `form:"from" binding:"required"`
To string `form:"to" binding:"required"`
}
type GetMessageStatisticsRequest struct {
GetStatisticsRequest
}
type GetMessageStatisticsResponse struct {
PrivateMessageNum int `json:"private_message_num"`
GroupMessageNum int `json:"group_message_num"`
PrivateMessageNumList []struct {
Date string `json:"date"`
MessageNum int `json:"message_num"`
} `json:"private_message_num_list"`
GroupMessageNumList []struct {
Date string `json:"date"`
MessageNum int `json:"message_num"`
} `json:"group_message_num_list"`
}
type GetUserStatisticsRequest struct {
GetStatisticsRequest
}
type GetUserStatisticsResponse struct {
IncreaseUserNum int `json:"increase_user_num"`
ActiveUserNum int `json:"active_user_num"`
TotalUserNum int `json:"total_user_num"`
IncreaseUserNumList []struct {
Date string `json:"date"`
IncreaseUserNum int `json:"increase_user_num"`
} `json:"increase_user_num_list"`
ActiveUserNumList []struct {
Date string `json:"date"`
ActiveUserNum int `json:"active_user_num"`
} `json:"active_user_num_list"`
TotalUserNumList []struct {
Date string `json:"date"`
TotalUserNum int `json:"total_user_num"`
} `json:"total_user_num_list"`
}
type GetGroupStatisticsRequest struct {
GetStatisticsRequest
}
// 群聊统计
type GetGroupStatisticsResponse struct {
IncreaseGroupNum int `json:"increase_group_num"`
TotalGroupNum int `json:"total_group_num"`
IncreaseGroupNumList []struct {
Date string `json:"date"`
IncreaseGroupNum int `json:"increase_group_num"`
} `json:"increase_group_num_list"`
TotalGroupNumList []struct {
Date string `json:"date"`
TotalGroupNum int `json:"total_group_num"`
} `json:"total_group_num_list"`
}
type GetActiveUserRequest struct {
GetStatisticsRequest
// RequestPagination
}
type GetActiveUserResponse struct {
ActiveUserList []struct {
NickName string `json:"nick_name"`
UserId string `json:"user_id"`
MessageNum int `json:"message_num"`
} `json:"active_user_list"`
}
type GetActiveGroupRequest struct {
GetStatisticsRequest
// RequestPagination
}
type GetActiveGroupResponse struct {
ActiveGroupList []struct {
GroupName string `json:"group_name"`
GroupId string `json:"group_id"`
MessageNum int `json:"message_num"`
} `json:"active_group_list"`
}

@ -0,0 +1,110 @@
package cms_api_struct
type UserResponse struct {
ProfilePhoto string `json:"profile_photo"`
Nickname string `json:"nick_name"`
UserId string `json:"user_id"`
CreateTime string `json:"create_time,omitempty"`
IsBlock bool `json:"is_block"`
}
type GetUserRequest struct {
UserId string `form:"user_id" binding:"required"`
}
type GetUserResponse struct {
UserResponse
}
type GetUsersRequest struct {
RequestPagination
}
type GetUsersResponse struct {
Users []*UserResponse `json:"users"`
ResponsePagination
UserNums int32 `json:"user_nums"`
}
type GetUsersByNameRequest struct {
UserName string `form:"user_name" binding:"required"`
RequestPagination
}
type GetUsersByNameResponse struct {
Users []*UserResponse `json:"users"`
ResponsePagination
UserNums int32 `json:"user_nums"`
}
type ResignUserRequest struct {
UserId string `json:"user_id"`
}
type ResignUserResponse struct {
}
type AlterUserRequest struct {
UserId string `json:"user_id" binding:"required"`
Nickname string `json:"nickname"`
PhoneNumber int `json:"phone_number" validate:"len=11"`
Email string `json:"email"`
}
type AlterUserResponse struct {
}
type AddUserRequest struct {
PhoneNumber string `json:"phone_number" binding:"required"`
UserId string `json:"user_id" binding:"required"`
Name string `json:"name" binding:"required"`
}
type AddUserResponse struct {
}
type BlockUser struct {
UserResponse
BeginDisableTime string `json:"begin_disable_time"`
EndDisableTime string `json:"end_disable_time"`
}
type BlockUserRequest struct {
UserId string `json:"user_id" binding:"required"`
EndDisableTime string `json:"end_disable_time" binding:"required"`
}
type BlockUserResponse struct {
}
type UnblockUserRequest struct {
UserId string `json:"user_id" binding:"required"`
}
type UnBlockUserResponse struct {
}
type GetBlockUsersRequest struct {
RequestPagination
}
type GetBlockUsersResponse struct {
BlockUsers []BlockUser `json:"block_users"`
ResponsePagination
UserNums int32 `json:"user_nums"`
}
type GetBlockUserRequest struct {
UserId string `form:"user_id" binding:"required"`
}
type GetBlockUserResponse struct {
BlockUser
}
type DeleteUserRequest struct {
UserId string `json:"user_id" binding:"required"`
}
type DeleteUserResponse struct {
}

@ -77,6 +77,7 @@ type config struct {
RpcGetTokenPort []int `yaml:"rpcGetTokenPort"`
}
RpcRegisterName struct {
OpenImStatisticsName string `yaml:"OpenImStatisticsName"`
OpenImUserName string `yaml:"openImUserName"`
OpenImFriendName string `yaml:"openImFriendName"`
OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"`
@ -84,6 +85,8 @@ type config struct {
OpenImOnlineMessageRelayName string `yaml:"openImOnlineMessageRelayName"`
OpenImGroupName string `yaml:"openImGroupName"`
OpenImAuthName string `yaml:"openImAuthName"`
OpenImMessageCMSName string `yaml:"openImMessageCMSName"`
OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
}
Etcd struct {
EtcdSchema string `yaml:"etcdSchema"`

@ -109,6 +109,16 @@ const (
IsUnreadCount = "unreadCount"
IsConversationUpdate = "conversationUpdate"
IsSenderSync = "senderSync"
//GroupStatus
GroupOk = 0
GroupBanChat = 1
GroupDisband = 2
GroupBaned = 3
GroupBanPrivateChat = 4
//UserJoinGroupSource
JoinByAdmin = 1
)
var ContentType2PushContent = map[int64]string{
@ -147,3 +157,17 @@ const (
)
const FriendAcceptTip = "You have successfully become friends, so start chatting"
func GroupIsBanChat(status int32) bool {
if status != GroupBanChat {
return false
}
return true
}
func GroupIsBanPrivateChat(status int32) bool {
if status != GroupBanPrivateChat {
return false
}
return true
}

@ -10,11 +10,12 @@ type ErrInfo struct {
var (
OK = ErrInfo{0, ""}
ErrServer = ErrInfo{500, "server error"}
// ErrMysql = ErrInfo{100, ""}
// ErrMongo = ErrInfo{110, ""}
// ErrRedis = ErrInfo{120, ""}
ErrParseToken = ErrInfo{200, ParseTokenMsg.Error()}
ErrParseToken = ErrInfo{700, ParseTokenMsg.Error()}
// ErrCreateToken = ErrInfo{201, "Create token failed"}
// ErrAppServerKey = ErrInfo{300, "key error"}
ErrTencentCredential = ErrInfo{400, ThirdPartyMsg.Error()}
@ -86,6 +87,10 @@ const (
IntentionalError = 10007
)
func (e *ErrInfo) Error() string {
func (e ErrInfo) Error() string {
return e.ErrMsg
}
func (e *ErrInfo) Code() int32 {
return e.ErrCode
}

@ -193,3 +193,9 @@ type ChatLog struct {
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
type BlackList struct {
UserId string `gorm:"column:uid"`
BeginDisableTime time.Time `gorm:"column:begin_disable_time"`
EndDisableTime time.Time `gorm:"column:end_disable_time"`
}

@ -4,10 +4,11 @@ import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/log"
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"sync"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type mysqlDB struct {

@ -4,6 +4,7 @@ import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"fmt"
"time"
)
@ -225,6 +226,31 @@ func IsGroupOwnerAdmin(groupID, UserID string) bool {
return false
}
func GetGroupMembersByGroupIdCMS(groupId string, userName string, showNumber, pageNumber int32) ([]db.GroupMember, error) {
var groupMembers []db.GroupMember
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return groupMembers, err
}
err = dbConn.Table("group_members").Where("group_id=?", groupId).Where(fmt.Sprintf(" nickname like '%%%s%%' ", userName)).Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&groupMembers).Error
if err != nil {
return nil, err
}
return groupMembers, nil
}
func GetGroupMembersCount(groupId, userName string) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var count int32
if err != nil {
return count, err
}
dbConn.LogMode(true)
if err := dbConn.Table("group_members").Where("group_id=?", groupId).Where(fmt.Sprintf(" nickname like '%%%s%%' ", userName)).Count(&count).Error; err != nil {
return count, err
}
return count, nil
}
//
//func SelectGroupList(groupID string) ([]string, error) {

@ -1,8 +1,11 @@
package im_mysql_model
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"errors"
"fmt"
"time"
)
@ -53,6 +56,126 @@ func SetGroupInfo(groupInfo db.Group) error {
if err != nil {
return err
}
dbConn.LogMode(true)
err = dbConn.Table("groups").Where("group_id=?", groupInfo.GroupID).Update(&groupInfo).Error
return err
}
func GetGroupsByName(groupName string, pageNumber, showNumber int32) ([]db.Group, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var groups []db.Group
if err != nil {
return groups, err
}
dbConn.LogMode(true)
err = dbConn.Table("groups").Where(fmt.Sprintf(" name like '%%%s%%' ", groupName)).Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&groups).Error
return groups, err
}
func GetGroups(pageNumber, showNumber int) ([]db.Group, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var groups []db.Group
if err != nil {
return groups, err
}
dbConn.LogMode(true)
if err = dbConn.Table("groups").Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&groups).Error; err != nil {
return groups, err
}
return groups, nil
}
func OperateGroupStatus(groupId string, groupStatus int32) error {
group := db.Group{
GroupID: groupId,
Status: groupStatus,
}
if err := SetGroupInfo(group); err != nil {
return err
}
return nil
}
func DeleteGroup(groupId string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(true)
var group db.Group
var groupMembers []db.GroupMember
if err := dbConn.Table("groups").Where("group_id=?", groupId).Delete(&group).Error; err != nil {
return err
}
if err := dbConn.Table("group_members").Where("group_id=?", groupId).Delete(groupMembers).Error; err != nil {
return err
}
return nil
}
func OperateGroupRole(userId, groupId string, roleLevel int32) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(true)
groupMember := db.GroupMember{
UserID: userId,
GroupID: groupId,
RoleLevel: roleLevel,
}
updateInfo := db.GroupMember{
RoleLevel: roleLevel,
}
result := dbConn.Table("group_members").Find(&groupMember).Update(updateInfo)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return errors.New(fmt.Sprintf("user %s not exist in group %s or already operate", userId, groupId))
}
return nil
}
func GetGroupsCountNum(group db.Group) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var count int32
if err := dbConn.Table("groups").Where(fmt.Sprintf(" name like '%%%s%%' ", group.GroupName)).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func GetGroupById(groupId string) (db.Group, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
group := db.Group{
GroupID: groupId,
}
if err != nil {
return group, err
}
dbConn.LogMode(true)
if err := dbConn.Table("groups").Find(&group).Error; err != nil {
return group, err
}
return group, nil
}
func GetGroupMaster(groupId string) (db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
groupMember := db.GroupMember{}
if err != nil {
return groupMember, err
}
dbConn.LogMode(true)
if err := dbConn.Table("group_members").Where("role_level=? and group_id=?", constant.GroupOwner, groupId).Find(&groupMember).Error; err != nil {
return groupMember, err
}
return groupMember, nil
}

@ -0,0 +1,29 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"fmt"
)
func GetChatLog(chatLog db.ChatLog, pageNumber, showNumber int32) ([]db.ChatLog, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var chatLogs []db.ChatLog
if err != nil {
return chatLogs, err
}
dbConn.LogMode(true)
err = dbConn.Table("chat_logs").Where(fmt.Sprintf(" content like '%%%s%%'", chatLog.Content)).
Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&chatLogs).Error
return chatLogs, err
}
func GetChatLogCount(chatLog db.ChatLog) (int64, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var count int64
if err != nil {
return count, err
}
dbConn.LogMode(true)
err = dbConn.Table("chat_logs").Where(fmt.Sprintf(" content like '%%%s%%' and ", chatLog.Content)).Count(&count).Error
return count, err
}

@ -0,0 +1,153 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"time"
)
func GetActiveUserNum(from, to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("chat_logs").Select("count(distinct(send_id))").Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func GetIncreaseUserNum(from, to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("users").Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func GetTotalUserNum() (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("users").Count(&num).Error
return num, err
}
func GetTotalUserNumByDate(to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("users").Where("create_time <= ?", to).Count(&num).Error
return num, err
}
func GetPrivateMessageNum(from, to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("chat_logs").Where("create_time >= ? and create_time <= ? and session_type = ?", from, to, 1).Count(&num).Error
return num, err
}
func GetGroupMessageNum(from, to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("chat_logs").Where("create_time >= ? and create_time <= ? and session_type = ?", from, to, 2).Count(&num).Error
return num, err
}
func GetIncreaseGroupNum(from, to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("groups").Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func GetTotalGroupNum() (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("groups").Count(&num).Error
return num, err
}
func GetGroupNum(to time.Time) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var num int32
err = dbConn.Table("groups").Where("create_time <= ?", to).Count(&num).Error
return num, err
}
type activeGroup struct {
Name string
Id string `gorm:"column:recv_id"`
MessageNum int `gorm:"column:message_num"`
}
func GetActiveGroups(from, to time.Time, limit int) ([]*activeGroup, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var activeGroups []*activeGroup
if err != nil {
return activeGroups, err
}
dbConn.LogMode(true)
err = dbConn.Table("chat_logs").Select("recv_id, count(*) as message_num").Where("create_time >= ? and create_time <= ? and session_type = ?", from, to, 2).Group("recv_id").Limit(limit).Order("message_num DESC").Find(&activeGroups).Error
for _, activeGroup := range activeGroups {
group := db.Group{
GroupID: activeGroup.Id,
}
dbConn.Model(&group).Select("group_id", "name").Find(&group)
activeGroup.Name = group.GroupName
}
return activeGroups, err
}
type activeUser struct {
Name string
Id string `gorm:"column:send_id"`
MessageNum int `gorm:"column:message_num"`
}
func GetActiveUsers(from, to time.Time, limit int) ([]*activeUser, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var activeUsers []*activeUser
if err != nil {
return activeUsers, err
}
dbConn.LogMode(true)
err = dbConn.Table("chat_logs").Select("send_id, count(*) as message_num").Where("create_time >= ? and create_time <= ? and session_type = ?", from, to, 1).Group("send_id").Limit(limit).Order("message_num DESC").Find(&activeUsers).Error
for _, activeUser := range activeUsers {
user := db.User{
UserID: activeUser.Id,
}
dbConn.Table("users").Select("user_id, name").Find(&user)
activeUser.Name = user.Nickname
}
return activeUsers, err
}

@ -6,8 +6,9 @@ import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"fmt"
_ "github.com/jinzhu/gorm/dialects/mysql"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func init() {
@ -43,24 +44,24 @@ func UserRegister(user db.User) error {
if user.Birth.Unix() < 0 {
user.Birth = utils.UnixSecondToTime(0)
}
err = dbConn.Table("users").Create(&user).Error
err = dbConn.Debug().Table("users").Create(&user).Error
if err != nil {
return err
}
return nil
}
//type User struct {
// UserID string `gorm:"column:user_id;primaryKey;"`
// Nickname string `gorm:"column:name"`
// FaceUrl string `gorm:"column:icon"`
// Gender int32 `gorm:"column:gender"`
// PhoneNumber string `gorm:"column:phone_number"`
// Birth string `gorm:"column:birth"`
// Email string `gorm:"column:email"`
// Ex string `gorm:"column:ex"`
// CreateTime time.Time `gorm:"column:create_time"`
//}
type User struct {
UserID string `gorm:"column:user_id;primaryKey;"`
Nickname string `gorm:"column:name"`
FaceUrl string `gorm:"column:icon"`
Gender int32 `gorm:"column:gender"`
PhoneNumber string `gorm:"column:phone_number"`
Birth string `gorm:"column:birth"`
Email string `gorm:"column:email"`
Ex string `gorm:"column:ex"`
CreateTime time.Time `gorm:"column:create_time"`
}
func DeleteUser(userID string) (i int64) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
@ -89,7 +90,7 @@ func UpdateUserInfo(user db.User) error {
if err != nil {
return err
}
dbConn.LogMode(true)
err = dbConn.Table("users").Where("user_id=?", user.UserID).Update(&user).Error
return err
}
@ -121,3 +122,184 @@ func SelectSomeUserID(userIDList []string) ([]string, error) {
}
return resultArr, nil
}
func GetUsers(showNumber, pageNumber int32) ([]db.User, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var users []db.User
if err != nil {
return users, err
}
dbConn.LogMode(true)
err = dbConn.Table("users").Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&users).Error
if err != nil {
return users, err
}
return users, err
}
func AddUser(userId, phoneNumber, name string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
user := db.User{
PhoneNumber: phoneNumber,
Birth: time.Now(),
CreateTime: time.Now(),
UserID: userId,
Nickname: name,
}
result := dbConn.Table("users").Create(&user)
return result.Error
}
func UserIsBlock(userId string) (bool, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return false, err
}
var user db.BlackList
rows := dbConn.Table("black_lists").Where("uid=?", userId).First(&user).RowsAffected
if rows >= 1 {
return true, nil
}
return false, nil
}
func BlockUser(userId, endDisableTime string) error {
user, err := GetUserByUserID(userId)
if err != nil || user.UserID == "" {
return err
}
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
end, err := time.Parse("2006-01-02 15:04:05", endDisableTime)
if err != nil {
return err
}
if end.Before(time.Now()) {
return constant.ErrDB
}
var blockUser db.BlackList
dbConn.Table("black_lists").Where("uid=?", userId).First(&blockUser)
if blockUser.UserId != "" {
dbConn.Model(&blockUser).Where("uid=?", blockUser.UserId).Update("end_disable_time", end)
return nil
}
blockUser = db.BlackList{
UserId: userId,
BeginDisableTime: time.Now(),
EndDisableTime: end,
}
result := dbConn.Create(&blockUser)
return result.Error
}
func UnBlockUser(userId string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(true)
result := dbConn.Where("uid=?", userId).Delete(&db.BlackList{})
return result.Error
}
type BlockUserInfo struct {
User db.User
BeginDisableTime time.Time
EndDisableTime time.Time
}
func GetBlockUserById(userId string) (BlockUserInfo, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var blockUserInfo BlockUserInfo
blockUser := db.BlackList{
UserId: userId,
}
if err != nil {
return blockUserInfo, err
}
if err = dbConn.Table("black_lists").Where("uid=?", userId).Find(&blockUser).Error; err != nil {
return blockUserInfo, err
}
user := db.User{
UserID: blockUser.UserId,
}
if err := dbConn.Find(&user).Error; err != nil {
return blockUserInfo, err
}
blockUserInfo.User.UserID = user.UserID
blockUserInfo.User.FaceURL = user.UserID
blockUserInfo.User.Nickname = user.Nickname
blockUserInfo.BeginDisableTime = blockUser.BeginDisableTime
blockUserInfo.EndDisableTime = blockUser.EndDisableTime
return blockUserInfo, nil
}
func GetBlockUsers(showNumber, pageNumber int32) ([]BlockUserInfo, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var blockUserInfos []BlockUserInfo
var blockUsers []db.BlackList
if err != nil {
return blockUserInfos, err
}
dbConn.LogMode(true)
if err = dbConn.Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&blockUsers).Error; err != nil {
return blockUserInfos, err
}
for _, blockUser := range blockUsers {
var user db.User
if err := dbConn.Table("users").Where("user_id=?", blockUser.UserId).First(&user).Error; err == nil {
blockUserInfos = append(blockUserInfos, BlockUserInfo{
User: db.User{
UserID: user.UserID,
Nickname: user.Nickname,
FaceURL: user.FaceURL,
},
BeginDisableTime: blockUser.BeginDisableTime,
EndDisableTime: blockUser.EndDisableTime,
})
}
}
return blockUserInfos, nil
}
func GetUserByName(userName string, showNumber, pageNumber int32) ([]db.User, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var users []db.User
if err != nil {
return users, err
}
dbConn.LogMode(true)
err = dbConn.Table("users").Where(fmt.Sprintf(" name like '%%%s%%' ", userName)).Limit(showNumber).Offset(showNumber * (pageNumber - 1)).Find(&users).Error
return users, err
}
func GetUsersCount(user db.User) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var count int32
if err := dbConn.Table("users").Where(fmt.Sprintf(" name like '%%%s%%' ", user.Nickname)).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func GetBlockUsersNumCount() (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
dbConn.LogMode(true)
var count int32
if err := dbConn.Model(&db.BlackList{}).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}

@ -0,0 +1,43 @@
package http
import (
"Open_IM/pkg/common/constant"
"fmt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
//"Open_IM/pkg/cms_api_struct"
"net/http"
"github.com/gin-gonic/gin"
)
type BaseResp struct {
Code int32 `json:"code"`
ErrMsg string `json:"err_msg"`
Data interface{} `json:"data"`
}
func RespHttp200(ctx *gin.Context, err error, data interface{}) {
var resp BaseResp
switch e := err.(type) {
case constant.ErrInfo:
resp.Code = e.ErrCode
resp.ErrMsg = e.ErrMsg
default:
s, ok := status.FromError(err)
if !ok {
fmt.Println("need grpc format error")
return
}
resp.Code = int32(s.Code())
resp.ErrMsg = s.Message()
}
resp.Data = data
ctx.JSON(http.StatusOK, resp)
}
// warp error
func WrapError(err constant.ErrInfo) error {
return status.Error(codes.Code(err.ErrCode), err.ErrMsg)
}

@ -2,14 +2,14 @@ package log
import (
"Open_IM/pkg/common/config"
"bufio"
"fmt"
"os"
"time"
nested "github.com/antonfisher/nested-logrus-formatter"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"os"
"time"
)
var logger *Logger
@ -32,12 +32,13 @@ func loggerInit(moduleName string) *Logger {
//All logs will be printed
logger.SetLevel(logrus.Level(config.Config.Log.RemainLogLevel))
//Close std console output
src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
panic(err.Error())
}
writer := bufio.NewWriter(src)
logger.SetOutput(writer)
// src, err := os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
// if err != nil {
// panic(err.Error())
// }
// writer := bufio.NewWriter(src)
// logger.SetOutput(writer)
logger.SetOutput(os.Stdout)
//Log Console Print Style Setting
logger.SetFormatter(&nested.Formatter{
TimestampFormat: "2006-01-02 15:04:05.000",

@ -0,0 +1,317 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.15.5
// source: admin_cms/admin_cms.proto
package admin_cms
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type AdminLoginReq struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
OperationID string `protobuf:"bytes,1,opt,name=OperationID,proto3" json:"OperationID,omitempty"`
AdminID string `protobuf:"bytes,2,opt,name=AdminID,proto3" json:"AdminID,omitempty"`
Secret string `protobuf:"bytes,3,opt,name=Secret,proto3" json:"Secret,omitempty"`
}
func (x *AdminLoginReq) Reset() {
*x = AdminLoginReq{}
if protoimpl.UnsafeEnabled {
mi := &file_admin_cms_admin_cms_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AdminLoginReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AdminLoginReq) ProtoMessage() {}
func (x *AdminLoginReq) ProtoReflect() protoreflect.Message {
mi := &file_admin_cms_admin_cms_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AdminLoginReq.ProtoReflect.Descriptor instead.
func (*AdminLoginReq) Descriptor() ([]byte, []int) {
return file_admin_cms_admin_cms_proto_rawDescGZIP(), []int{0}
}
func (x *AdminLoginReq) GetOperationID() string {
if x != nil {
return x.OperationID
}
return ""
}
func (x *AdminLoginReq) GetAdminID() string {
if x != nil {
return x.AdminID
}
return ""
}
func (x *AdminLoginReq) GetSecret() string {
if x != nil {
return x.Secret
}
return ""
}
type AdminLoginResp struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"`
}
func (x *AdminLoginResp) Reset() {
*x = AdminLoginResp{}
if protoimpl.UnsafeEnabled {
mi := &file_admin_cms_admin_cms_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AdminLoginResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AdminLoginResp) ProtoMessage() {}
func (x *AdminLoginResp) ProtoReflect() protoreflect.Message {
mi := &file_admin_cms_admin_cms_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AdminLoginResp.ProtoReflect.Descriptor instead.
func (*AdminLoginResp) Descriptor() ([]byte, []int) {
return file_admin_cms_admin_cms_proto_rawDescGZIP(), []int{1}
}
func (x *AdminLoginResp) GetToken() string {
if x != nil {
return x.Token
}
return ""
}
var File_admin_cms_admin_cms_proto protoreflect.FileDescriptor
var file_admin_cms_admin_cms_proto_rawDesc = []byte{
0x0a, 0x19, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x6d, 0x73, 0x2f, 0x61, 0x64, 0x6d, 0x69,
0x6e, 0x5f, 0x63, 0x6d, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x09, 0x61, 0x64, 0x6d,
0x69, 0x6e, 0x5f, 0x63, 0x6d, 0x73, 0x22, 0x63, 0x0a, 0x0d, 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x4c,
0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x12, 0x20, 0x0a, 0x0b, 0x4f, 0x70, 0x65, 0x72, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x4f, 0x70,
0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x44, 0x12, 0x18, 0x0a, 0x07, 0x41, 0x64, 0x6d,
0x69, 0x6e, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x41, 0x64, 0x6d, 0x69,
0x6e, 0x49, 0x44, 0x12, 0x16, 0x0a, 0x06, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x18, 0x03, 0x20,
0x01, 0x28, 0x09, 0x52, 0x06, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x22, 0x26, 0x0a, 0x0e, 0x41,
0x64, 0x6d, 0x69, 0x6e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x14, 0x0a,
0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f,
0x6b, 0x65, 0x6e, 0x32, 0x4d, 0x0a, 0x08, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x43, 0x4d, 0x53, 0x12,
0x41, 0x0a, 0x0a, 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x18, 0x2e,
0x61, 0x64, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x6d, 0x73, 0x2e, 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x4c,
0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65, 0x71, 0x1a, 0x19, 0x2e, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x5f,
0x63, 0x6d, 0x73, 0x2e, 0x41, 0x64, 0x6d, 0x69, 0x6e, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x52, 0x65,
0x73, 0x70, 0x42, 0x17, 0x5a, 0x15, 0x2e, 0x2f, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x6d,
0x73, 0x3b, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x6d, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_admin_cms_admin_cms_proto_rawDescOnce sync.Once
file_admin_cms_admin_cms_proto_rawDescData = file_admin_cms_admin_cms_proto_rawDesc
)
func file_admin_cms_admin_cms_proto_rawDescGZIP() []byte {
file_admin_cms_admin_cms_proto_rawDescOnce.Do(func() {
file_admin_cms_admin_cms_proto_rawDescData = protoimpl.X.CompressGZIP(file_admin_cms_admin_cms_proto_rawDescData)
})
return file_admin_cms_admin_cms_proto_rawDescData
}
var file_admin_cms_admin_cms_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_admin_cms_admin_cms_proto_goTypes = []interface{}{
(*AdminLoginReq)(nil), // 0: admin_cms.AdminLoginReq
(*AdminLoginResp)(nil), // 1: admin_cms.AdminLoginResp
}
var file_admin_cms_admin_cms_proto_depIdxs = []int32{
0, // 0: admin_cms.adminCMS.AdminLogin:input_type -> admin_cms.AdminLoginReq
1, // 1: admin_cms.adminCMS.AdminLogin:output_type -> admin_cms.AdminLoginResp
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_admin_cms_admin_cms_proto_init() }
func file_admin_cms_admin_cms_proto_init() {
if File_admin_cms_admin_cms_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_admin_cms_admin_cms_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AdminLoginReq); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_admin_cms_admin_cms_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AdminLoginResp); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_admin_cms_admin_cms_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_admin_cms_admin_cms_proto_goTypes,
DependencyIndexes: file_admin_cms_admin_cms_proto_depIdxs,
MessageInfos: file_admin_cms_admin_cms_proto_msgTypes,
}.Build()
File_admin_cms_admin_cms_proto = out.File
file_admin_cms_admin_cms_proto_rawDesc = nil
file_admin_cms_admin_cms_proto_goTypes = nil
file_admin_cms_admin_cms_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// AdminCMSClient is the client API for AdminCMS service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AdminCMSClient interface {
AdminLogin(ctx context.Context, in *AdminLoginReq, opts ...grpc.CallOption) (*AdminLoginResp, error)
}
type adminCMSClient struct {
cc grpc.ClientConnInterface
}
func NewAdminCMSClient(cc grpc.ClientConnInterface) AdminCMSClient {
return &adminCMSClient{cc}
}
func (c *adminCMSClient) AdminLogin(ctx context.Context, in *AdminLoginReq, opts ...grpc.CallOption) (*AdminLoginResp, error) {
out := new(AdminLoginResp)
err := c.cc.Invoke(ctx, "/admin_cms.adminCMS/AdminLogin", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// AdminCMSServer is the server API for AdminCMS service.
type AdminCMSServer interface {
AdminLogin(context.Context, *AdminLoginReq) (*AdminLoginResp, error)
}
// UnimplementedAdminCMSServer can be embedded to have forward compatible implementations.
type UnimplementedAdminCMSServer struct {
}
func (*UnimplementedAdminCMSServer) AdminLogin(context.Context, *AdminLoginReq) (*AdminLoginResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method AdminLogin not implemented")
}
func RegisterAdminCMSServer(s *grpc.Server, srv AdminCMSServer) {
s.RegisterService(&_AdminCMS_serviceDesc, srv)
}
func _AdminCMS_AdminLogin_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AdminLoginReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AdminCMSServer).AdminLogin(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/admin_cms.adminCMS/AdminLogin",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AdminCMSServer).AdminLogin(ctx, req.(*AdminLoginReq))
}
return interceptor(ctx, in, info, handler)
}
var _AdminCMS_serviceDesc = grpc.ServiceDesc{
ServiceName: "admin_cms.adminCMS",
HandlerType: (*AdminCMSServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "AdminLogin",
Handler: _AdminCMS_AdminLogin_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "admin_cms/admin_cms.proto",
}

@ -0,0 +1,18 @@
syntax = "proto3";
option go_package = "./admin_cms;admin_cms";
package admin_cms;
message AdminLoginReq {
string OperationID = 1;
string AdminID = 2;
string Secret = 3;
}
message AdminLoginResp {
string token = 1;
}
service adminCMS {
rpc AdminLogin(AdminLoginReq) returns(AdminLoginResp);
}

File diff suppressed because it is too large Load Diff

@ -208,6 +208,113 @@ message GetGroupAllMemberResp {
repeated server_api_params.GroupMemberFullInfo memberList = 3;
}
message CMSGroup {
server_api_params.GroupInfo GroupInfo = 1;
string GroupMasterName = 2;
string GroupMasterId = 3;
}
message GetGroupReq {
string GroupName = 1;
server_api_params.RequestPagination Pagination = 2;
string OperationID = 3;
}
message GetGroupResp {
repeated CMSGroup CMSGroups = 1;
server_api_params.RequestPagination Pagination = 2;
int32 GroupNums = 3;
}
message GetGroupsReq {
server_api_params.RequestPagination Pagination = 1;
string OperationID = 2;
}
message GetGroupsResp {
repeated CMSGroup CMSGroups = 1;
server_api_params.RequestPagination Pagination = 2;
int32 GroupNum = 3;
}
message GetGroupMemberReq {
string GroupId = 1;
string OperationID = 2;
}
message OperateGroupStatusReq {
string GroupId = 1;
int32 Status = 2;
string OperationID = 3;
}
message OperateGroupStatusResp {
}
message OperateUserRoleReq {
string GroupId = 1;
string UserId = 2;
int32 RoleLevel = 3;
string OperationID = 4;
}
message OperateUserRoleResp {
}
message DeleteGroupReq {
string GroupId = 1;
string OperationID = 2;
}
message DeleteGroupResp {
}
message GetGroupByIdReq {
string GroupId = 1;
string OperationID = 2;
}
message GetGroupByIdResp {
CMSGroup CMSGroup = 1;
}
message GetGroupMembersCMSReq {
string GroupId = 1;
string UserName = 2;
server_api_params.RequestPagination Pagination = 3;
string OperationID = 4;
}
message GetGroupMembersCMSResp {
repeated server_api_params.GroupMemberFullInfo members = 1;
server_api_params.ResponsePagination Pagination = 2;
int32 MemberNums = 3;
}
message RemoveGroupMembersCMSReq {
string GroupId = 1;
repeated string UserIds = 2;
string OperationID = 3;
}
message RemoveGroupMembersCMSResp {
repeated string success = 1;
repeated string failed = 2;
}
message AddGroupMembersCMSReq {
string GroupId = 1;
repeated string UserIds = 2;
string OperationId = 3;
}
message AddGroupMembersCMSResp {
repeated string success = 1;
repeated string failed = 2;
}
service group{
@ -226,6 +333,16 @@ service group{
rpc getJoinedGroupList(GetJoinedGroupListReq) returns (GetJoinedGroupListResp);
rpc inviteUserToGroup(InviteUserToGroupReq) returns (InviteUserToGroupResp);
rpc getGroupAllMember(GetGroupAllMemberReq) returns(GetGroupAllMemberResp);
rpc GetGroupById(GetGroupByIdReq) returns(GetGroupByIdResp);
rpc GetGroup(GetGroupReq) returns(GetGroupResp);
rpc GetGroups(GetGroupsReq) returns(GetGroupsResp);
rpc OperateGroupStatus(OperateGroupStatusReq) returns(OperateGroupStatusResp);
rpc OperateUserRole(OperateUserRoleReq) returns(OperateUserRoleResp);
rpc DeleteGroup(DeleteGroupReq) returns(DeleteGroupResp);
rpc GetGroupMembersCMS(GetGroupMembersCMSReq) returns(GetGroupMembersCMSResp);
rpc RemoveGroupMembersCMS(RemoveGroupMembersCMSReq) returns(RemoveGroupMembersCMSResp);
rpc AddGroupMembersCMS(AddGroupMembersCMSReq) returns(AddGroupMembersCMSResp);
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,70 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./message_cms;message_cms";
package message_cms;
message BoradcastMessageReq {
string Message = 1;
string OperationID = 2;
}
message BoradcastMessageResp {
}
message MassSendMessageReq {
string Message = 1;
repeated string UserIds = 2;
string OperationID = 3;
}
message MassSendMessageResp {
}
message GetChatLogsReq {
string Content = 1;
string UserId = 2;
string GroupId = 3;
string Date = 4;
int32 SessionType = 5;
int32 ContentType = 6;
server_api_params.RequestPagination Pagination = 7;
string OperationID = 8;
}
message ChatLogs {
int32 SessionType = 1;
int32 ContentType = 2;
string SenderNickName = 3;
string SenderId = 4;
string ReciverNickName = 5;
string ReciverId = 6;
string SearchContent = 7;
string WholeContent = 8;
string GroupId = 9;
string GroupName = 10;
string Date = 11;
}
message GetChatLogsResp {
repeated ChatLogs ChatLogs = 1;
server_api_params.ResponsePagination Pagination = 2;
}
message WithdrawMessageReq {
string ServerMsgId = 1;
string OperationID = 2;
}
message WithdrawMessageResp {
}
service messageCMS {
rpc BoradcastMessage(BoradcastMessageReq) returns(BoradcastMessageResp);
rpc MassSendMessage(MassSendMessageReq) returns(MassSendMessageResp);
rpc GetChatLogs(GetChatLogsReq) returns(GetChatLogsResp);
rpc WithdrawMessage(WithdrawMessageReq) returns(WithdrawMessageResp);
}

@ -1,5 +1,8 @@
all_proto=(
message_cms/message_cms.proto
admin_cms/admin_cms.proto
statistics/statistics.proto
auth/auth.proto
friend/friend.proto
group/group.proto
@ -8,4 +11,5 @@ all_proto=(
push/push.proto
relay/relay.proto
sdk_ws/ws.proto
)

File diff suppressed because it is too large Load Diff

@ -1,4 +1,5 @@
syntax = "proto3";
option go_package = "./sdk_ws;server_api_params";
package server_api_params;//The package name to which the proto file belongs
//option go_package = "./sdk_ws;open_im_sdk";//The generated go pb file is in the current directory, and the package name is open_im_sdk
@ -330,3 +331,14 @@ message FriendInfoChangedTips{
message UserInfoUpdatedTips{
string userID = 1;
}
///cms
message RequestPagination {
int32 pageNumber = 1;
int32 showNumber = 2;
}
message ResponsePagination {
int32 CurrentPage = 5;
int32 ShowNumber = 6;
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,93 @@
syntax = "proto3";
// import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./statistics;statistics";
package statistics;
message StatisticsReq {
string from = 1;
string to = 2;
}
message GetActiveUserReq{
StatisticsReq StatisticsReq = 1;
string OperationID = 2;
}
message UserResp{
string NickName = 1;
string UserId = 2;
int32 MessageNum = 3;
}
message GetActiveUserResp {
repeated UserResp Users = 1;
}
message GetActiveGroupReq{
StatisticsReq StatisticsReq = 1;
string OperationID = 2;
}
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;
string OperationID = 2;
}
message GetMessageStatisticsResp {
int32 PrivateMessageNum = 1;
int32 GroupMessageNum = 2;
repeated DateNumList PrivateMessageNumList = 3;
repeated DateNumList GroupMessageNumList = 4;
}
message GetGroupStatisticsReq {
StatisticsReq StatisticsReq = 1;
string OperationID = 2;
}
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;
}
service user {
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);
}

File diff suppressed because it is too large Load Diff

@ -13,6 +13,7 @@ message DeleteUsersReq{
string OpUserID = 3;
string OperationID = 4;
}
message DeleteUsersResp{
CommonResp CommonResp = 1;
repeated string FailedUserIDList = 2;
@ -98,7 +99,7 @@ message GetReceiveMessageOptResp{
message GetAllConversationMsgOptReq{
string FromUserID = 1;
string operationID = 2;
string operationID = 2;
string OpUserID = 3;
}
message GetAllConversationMsgOptResp{
@ -106,6 +107,137 @@ message GetAllConversationMsgOptResp{
repeated OptResult conversationOptResultList = 3;
}
message ResignUserReq{
string UserId = 1;
string OperationID = 2;
}
message ResignUserResp{
CommonResp commonResp = 1;
}
message GetUserByIdReq{
string UserId = 1;
string OperationID = 2;
}
message User{
string ProfilePhoto = 1;
string Nickname = 2;
string UserId = 3;
string CreateTime = 4;
bool IsBlock = 5;
}
message GetUserByIdResp{
CommonResp CommonResp = 1;
User user = 2;
}
message GetUsersByNameReq {
string UserName = 1;
server_api_params.RequestPagination Pagination =2;
string OperationID = 3;
}
message GetUsersByNameResp {
repeated User users = 1;
server_api_params.ResponsePagination Pagination = 2;
int32 UserNums = 3;
}
message AlterUserReq{
string UserId = 1;
string OperationID = 2;
int64 PhoneNumber = 3;
string Nickname = 4;
string Email = 5;
}
message AlterUserResp{
CommonResp CommonResp = 1;
}
message GetUsersReq {
string OperationID = 1;
server_api_params.RequestPagination Pagination = 2;
string UserName = 3;
}
message GetUsersResp{
CommonResp CommonResp = 1;
repeated User user = 2;
server_api_params.ResponsePagination Pagination = 3;
int32 UserNums = 4;
}
message AddUserReq{
string OperationID = 1;
string PhoneNumber = 2;
string UserId = 3;
string name = 4;
}
message AddUserResp{
CommonResp CommonResp = 1;
}
message BlockUserReq{
string UserId = 1;
string EndDisableTime = 2;
string OperationID = 3;
}
message BlockUserResp{
CommonResp CommonResp = 1;
}
message UnBlockUserReq{
string UserId = 1;
string OperationID = 2;
}
message UnBlockUserResp{
CommonResp CommonResp = 1;
}
message GetBlockUsersReq{
server_api_params.RequestPagination Pagination =1;
string OperationID = 2;
int32 BlockUserNum = 3;
}
message BlockUser {
User User = 1;
string BeginDisableTime = 2;
string EndDisableTime = 3;
}
message GetBlockUsersResp{
CommonResp CommonResp = 1;
repeated BlockUser BlockUsers = 2;
server_api_params.ResponsePagination Pagination = 3;
int32 UserNums = 4;
}
message GetBlockUserByIdReq {
string User_id = 1;
string OperationID = 2;
}
message GetBlockUserByIdResp {
BlockUser BlockUser = 2;
}
message DeleteUserReq {
string User_id = 1;
string OperationID = 2;
}
message DeleteUserResp {
}
service user {
rpc GetUserInfo(GetUserInfoReq) returns(GetUserInfoResp);
@ -116,4 +248,16 @@ service user {
rpc GetReceiveMessageOpt(GetReceiveMessageOptReq)returns(GetReceiveMessageOptResp);
rpc GetAllConversationMsgOpt(GetAllConversationMsgOptReq)returns(GetAllConversationMsgOptResp);
rpc AccountCheck(AccountCheckReq)returns(AccountCheckResp);
rpc GetUserById(GetUserByIdReq) returns (GetUserByIdResp);
rpc GetUsersByName(GetUsersByNameReq) returns (GetUsersByNameResp);
rpc ResignUser(ResignUserReq) returns (ResignUserResp);
rpc AlterUser(AlterUserReq) returns (AlterUserResp);
rpc GetUsers(GetUsersReq) returns (GetUsersResp);
rpc AddUser(AddUserReq) returns (AddUserResp);
rpc BlockUser(BlockUserReq) returns (BlockUserResp);
rpc UnBlockUser(UnBlockUserReq) returns (UnBlockUserResp);
rpc GetBlockUsers(GetBlockUsersReq) returns (GetBlockUsersResp);
rpc GetBlockUserById(GetBlockUserByIdReq) returns (GetBlockUserByIdResp);
rpc DeleteUser(DeleteUserReq) returns (DeleteUserResp);
}

@ -78,3 +78,8 @@ func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 {
tm, _ := time.Parse(timeFormat, timeSrc)
return tm.Unix()
}
func TimeStringToTime(timeString string) (time.Time, error) {
t, err := time.Parse("2006-01-02", timeString)
return t, err
}

Loading…
Cancel
Save