v3 - main to cut out

This commit is contained in:
Xinwei Xiong(cubxxw-openim)
2023-06-29 22:35:31 +08:00
commit 6d499032fa
293 changed files with 57778 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
package base_info
//UserID string `protobuf:"bytes,1,opt,name=UserID" json:"UserID,omitempty"`
// Nickname string `protobuf:"bytes,2,opt,name=Nickname" json:"Nickname,omitempty"`
// FaceUrl string `protobuf:"bytes,3,opt,name=FaceUrl" json:"FaceUrl,omitempty"`
// Gender int32 `protobuf:"varint,4,opt,name=Gender" json:"Gender,omitempty"`
// PhoneNumber string `protobuf:"bytes,5,opt,name=PhoneNumber" json:"PhoneNumber,omitempty"`
// Birth string `protobuf:"bytes,6,opt,name=Birth" json:"Birth,omitempty"`
// Email string `protobuf:"bytes,7,opt,name=Email" json:"Email,omitempty"`
// Ex string `protobuf:"bytes,8,opt,name=Ex" json:"Ex,omitempty"`
type UserRegisterReq struct {
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=7"`
ApiUserInfo
OperationID string `json:"operationID" binding:"required"`
}
type UserTokenInfo struct {
UserID string `json:"userID"`
Token string `json:"token"`
ExpiredTime int64 `json:"expiredTime"`
}
type UserRegisterResp struct {
CommResp
UserToken UserTokenInfo `json:"data"`
}
type UserTokenReq struct {
Secret string `json:"secret" binding:"required,max=32"`
Platform int32 `json:"platform" binding:"required,min=1,max=8"`
UserID string `json:"userID" binding:"required,min=1,max=64"`
OperationID string `json:"operationID" binding:"required"`
}
type UserTokenResp struct {
CommResp
UserToken UserTokenInfo `json:"data"`
}
+117
View File
@@ -0,0 +1,117 @@
package base_info
type OptResult struct {
ConversationID string `json:"conversationID"`
Result *int32 `json:"result"`
}
type GetAllConversationMessageOptReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetAllConversationMessageOptResp struct {
CommResp
ConversationOptResultList []*OptResult `json:"data"`
}
type GetReceiveMessageOptReq struct {
ConversationIDList []string `json:"conversationIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetReceiveMessageOptResp struct {
CommResp
ConversationOptResultList []*OptResult `json:"data"`
}
type SetReceiveMessageOptReq struct {
FromUserID string `json:"fromUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
Opt *int32 `json:"opt" binding:"required"`
ConversationIDList []string `json:"conversationIDList" binding:"required"`
}
type SetReceiveMessageOptResp struct {
CommResp
ConversationOptResultList []*OptResult `json:"data"`
}
type Conversation struct {
OwnerUserID string `json:"ownerUserID" binding:"required"`
ConversationID string `json:"conversationID" binding:"required"`
ConversationType int32 `json:"conversationType" binding:"required"`
UserID string `json:"userID"`
GroupID string `json:"groupID"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
UnreadCount int32 `json:"unreadCount" binding:"omitempty"`
DraftTextTime int64 `json:"draftTextTime"`
IsPinned bool `json:"isPinned" binding:"omitempty"`
IsPrivateChat bool `json:"isPrivateChat"`
AttachedInfo string `json:"attachedInfo"`
Ex string `json:"ex"`
}
type SetConversationReq struct {
Conversation
NotificationType int32 `json:"notificationType"`
OperationID string `json:"operationID" binding:"required"`
}
type SetConversationResp struct {
CommResp
}
type BatchSetConversationsReq struct {
Conversations []Conversation `json:"conversations" binding:"required"`
NotificationType int32 `json:"notificationType"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type BatchSetConversationsResp struct {
CommResp
Data struct {
Success []string `json:"success"`
Failed []string `json:"failed"`
} `json:"data"`
}
type GetConversationReq struct {
ConversationID string `json:"conversationID" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetConversationResp struct {
CommResp
Conversation Conversation `json:"data"`
}
type GetAllConversationsReq struct {
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetAllConversationsResp struct {
CommResp
Conversations []Conversation `json:"data"`
}
type GetConversationsReq struct {
ConversationIDs []string `json:"conversationIDs" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetConversationsResp struct {
CommResp
Conversations []Conversation `json:"data"`
}
type SetRecvMsgOptReq struct {
OwnerUserID string `json:"ownerUserID" binding:"required"`
ConversationID string `json:"conversationID"`
RecvMsgOpt int32 `json:"recvMsgOpt" binding:"omitempty,oneof=0 1 2"`
OperationID string `json:"operationID" binding:"required"`
NotificationType int32 `json:"notificationType"`
}
type SetRecvMsgOptResp struct {
CommResp
}
+20
View File
@@ -0,0 +1,20 @@
package base_info
import sts "github.com/tencentyun/qcloud-cos-sts-sdk/go"
type TencentCloudStorageCredentialReq struct {
OperationID string `json:"operationID"`
}
type TencentCloudStorageCredentialRespData struct {
*sts.CredentialResult
Region string `json:"region"`
Bucket string `json:"bucket"`
}
type TencentCloudStorageCredentialResp struct {
CommResp
CosData TencentCloudStorageCredentialRespData `json:"-"`
Data map[string]interface{} `json:"data"`
}
+136
View File
@@ -0,0 +1,136 @@
package base_info
import open_im_sdk "Open_IM/pkg/proto/sdk_ws"
type ParamsCommFriend struct {
OperationID string `json:"operationID" binding:"required"`
ToUserID string `json:"toUserID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type AddBlacklistReq struct {
ParamsCommFriend
}
type AddBlacklistResp struct {
CommResp
}
type ImportFriendReq struct {
FriendUserIDList []string `json:"friendUserIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type UserIDResult struct {
UserID string `json:"userID"`
Result int32 `json:"result"`
}
type ImportFriendResp struct {
CommResp
UserIDResultList []UserIDResult `json:"data"`
}
type AddFriendReq struct {
ParamsCommFriend
ReqMsg string `json:"reqMsg"`
}
type AddFriendResp struct {
CommResp
}
type AddFriendResponseReq struct {
ParamsCommFriend
Flag int32 `json:"flag" binding:"required,oneof=-1 0 1"`
HandleMsg string `json:"handleMsg"`
}
type AddFriendResponseResp struct {
CommResp
}
type DeleteFriendReq struct {
ParamsCommFriend
}
type DeleteFriendResp struct {
CommResp
}
type GetBlackListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetBlackListResp struct {
CommResp
BlackUserInfoList []*open_im_sdk.PublicUserInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
//type PublicUserInfo struct {
// UserID string `json:"userID"`
// Nickname string `json:"nickname"`
// FaceUrl string `json:"faceUrl"`
// Gender int32 `json:"gender"`
//}
type SetFriendRemarkReq struct {
ParamsCommFriend
Remark string `json:"remark" binding:"required"`
}
type SetFriendRemarkResp struct {
CommResp
}
type RemoveBlackListReq struct {
ParamsCommFriend
}
type RemoveBlackListResp struct {
CommResp
}
type IsFriendReq struct {
ParamsCommFriend
}
type Response struct {
Friend bool `json:"isFriend"`
}
type IsFriendResp struct {
CommResp
Response Response `json:"data"`
}
type GetFriendsInfoReq struct {
ParamsCommFriend
}
type GetFriendsInfoResp struct {
CommResp
FriendInfoList []*open_im_sdk.FriendInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetFriendListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetFriendListResp struct {
CommResp
FriendInfoList []*open_im_sdk.FriendInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetFriendApplyListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetFriendApplyListResp struct {
CommResp
FriendRequestList []*open_im_sdk.FriendRequest `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetSelfApplyListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetSelfApplyListResp struct {
CommResp
FriendRequestList []*open_im_sdk.FriendRequest `json:"-"`
Data []map[string]interface{} `json:"data"`
}
+222
View File
@@ -0,0 +1,222 @@
package base_info
import (
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
)
type CommResp struct {
ErrCode int32 `json:"errCode"`
ErrMsg string `json:"errMsg"`
}
type CommDataResp struct {
CommResp
Data []map[string]interface{} `json:"data"`
}
type KickGroupMemberReq struct {
GroupID string `json:"groupID" binding:"required"`
KickedUserIDList []string `json:"kickedUserIDList" binding:"required"`
Reason string `json:"reason"`
OperationID string `json:"operationID" binding:"required"`
}
type KickGroupMemberResp struct {
CommResp
UserIDResultList []*UserIDResult `json:"data"`
}
type GetGroupMembersInfoReq struct {
GroupID string `json:"groupID" binding:"required"`
MemberList []string `json:"memberList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetGroupMembersInfoResp struct {
CommResp
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type InviteUserToGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
InvitedUserIDList []string `json:"invitedUserIDList" binding:"required"`
Reason string `json:"reason"`
OperationID string `json:"operationID" binding:"required"`
}
type InviteUserToGroupResp struct {
CommResp
UserIDResultList []*UserIDResult `json:"data"`
}
type GetJoinedGroupListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"`
}
type GetJoinedGroupListResp struct {
CommResp
GroupInfoList []*open_im_sdk.GroupInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetGroupMemberListReq struct {
GroupID string `json:"groupID"`
Filter int32 `json:"filter"`
NextSeq int32 `json:"nextSeq"`
OperationID string `json:"operationID"`
}
type GetGroupMemberListResp struct {
CommResp
NextSeq int32 `json:"nextSeq"`
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetGroupAllMemberReq struct {
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetGroupAllMemberResp struct {
CommResp
MemberList []*open_im_sdk.GroupMemberFullInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type CreateGroupReq struct {
MemberList []*GroupAddMemberInfo `json:"memberList" binding:"required"`
OwnerUserID string `json:"ownerUserID" binding:"required"`
GroupType int32 `json:"groupType"`
GroupName string `json:"groupName"`
Notification string `json:"notification"`
Introduction string `json:"introduction"`
FaceURL string `json:"faceURL"`
Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"`
}
type CreateGroupResp struct {
CommResp
GroupInfo open_im_sdk.GroupInfo `json:"-"`
Data map[string]interface{} `json:"data"`
}
type GetGroupApplicationListReq struct {
OperationID string `json:"operationID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //作为管理员或群主收到的 进群申请
}
type GetGroupApplicationListResp struct {
CommResp
GroupRequestList []*open_im_sdk.GroupRequest `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type GetUserReqGroupApplicationListReq struct {
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type GetUserRespGroupApplicationResp struct {
CommResp
GroupRequestList []*open_im_sdk.GroupRequest `json:"-"`
}
type GetGroupInfoReq struct {
GroupIDList []string `json:"groupIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetGroupInfoResp struct {
CommResp
GroupInfoList []*open_im_sdk.GroupInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type ApplicationGroupResponseReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
FromUserID string `json:"fromUserID" binding:"required"` //application from FromUserID
HandledMsg string `json:"handledMsg"`
HandleResult int32 `json:"handleResult" binding:"required,oneof=-1 1"`
}
type ApplicationGroupResponseResp struct {
CommResp
}
type JoinGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
ReqMessage string `json:"reqMessage"`
OperationID string `json:"operationID" binding:"required"`
}
type JoinGroupResp struct {
CommResp
}
type QuitGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type QuitGroupResp struct {
CommResp
}
type SetGroupInfoReq struct {
GroupID string `json:"groupID" binding:"required"`
GroupName string `json:"groupName"`
Notification string `json:"notification"`
Introduction string `json:"introduction"`
FaceURL string `json:"faceURL"`
Ex string `json:"ex"`
OperationID string `json:"operationID" binding:"required"`
}
type SetGroupInfoResp struct {
CommResp
}
type TransferGroupOwnerReq struct {
GroupID string `json:"groupID" binding:"required"`
OldOwnerUserID string `json:"oldOwnerUserID" binding:"required"`
NewOwnerUserID string `json:"newOwnerUserID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type TransferGroupOwnerResp struct {
CommResp
}
type DismissGroupReq struct {
GroupID string `json:"groupID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DismissGroupResp struct {
CommResp
}
type MuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
MutedSeconds uint32 `json:"mutedSeconds" binding:"required"`
}
type MuteGroupMemberResp struct {
CommResp
}
type CancelMuteGroupMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type CancelMuteGroupMemberResp struct {
CommResp
}
type MuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
}
type MuteGroupResp struct {
CommResp
}
type CancelMuteGroupReq struct {
OperationID string `json:"operationID" binding:"required"`
GroupID string `json:"groupID" binding:"required"`
}
type CancelMuteGroupResp struct {
CommResp
}
+44
View File
@@ -0,0 +1,44 @@
package base_info
import (
pbRelay "Open_IM/pkg/proto/relay"
"Open_IM/pkg/proto/sdk_ws"
pbUser "Open_IM/pkg/proto/user"
)
type DeleteUsersReq struct {
OperationID string `json:"operationID" binding:"required"`
DeleteUserIDList []string `json:"deleteUserIDList" binding:"required"`
}
type DeleteUsersResp struct {
CommResp
FailedUserIDList []string `json:"data"`
}
type GetAllUsersUidReq struct {
OperationID string `json:"operationID" binding:"required"`
}
type GetAllUsersUidResp struct {
CommResp
UserIDList []string `json:"data"`
}
type GetUsersOnlineStatusReq struct {
OperationID string `json:"operationID" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required,lte=200"`
}
type GetUsersOnlineStatusResp struct {
CommResp
SuccessResult []*pbRelay.GetUsersOnlineStatusResp_SuccessResult `json:"data"`
}
type AccountCheckReq struct {
OperationID string `json:"operationID" binding:"required"`
CheckUserIDList []string `json:"checkUserIDList" binding:"required,lte=100"`
}
type AccountCheckResp struct {
CommResp
ResultList []*pbUser.AccountCheckResp_SingleUserStatus `json:"data"`
}
type ManagementSendMsgResp struct {
CommResp
ResultList server_api_params.UserSendMsgResp `json:"data"`
}
+25
View File
@@ -0,0 +1,25 @@
package base_info
type MinioStorageCredentialReq struct {
OperationID string `json:"operationID"`
}
type MiniostorageCredentialResp struct {
SecretAccessKey string `json:"secretAccessKey"`
AccessKeyID string `json:"accessKeyID"`
SessionToken string `json:"sessionToken"`
BucketName string `json:"bucketName"`
StsEndpointURL string `json:"stsEndpointURL"`
}
type MinioUploadFileReq struct {
OperationID string `form:"operationID" binding:"required"`
FileType int `form:"fileType" binding:"required"`
}
type MinioUploadFileResp struct {
URL string `json:"URL"`
NewName string `json:"newName"`
SnapshotURL string `json:"snapshotURL,omitempty"`
SnapshotNewName string `json:"snapshotName,omitempty"`
}
+12
View File
@@ -0,0 +1,12 @@
package base_info
type DelMsgReq struct {
OpUserID string `json:"opUserID,omitempty"`
UserID string `json:"userID,omitempty"`
SeqList []uint32 `json:"seqList,omitempty"`
OperationID string `json:"operationID,omitempty"`
}
type DelMsgResp struct {
CommResp
}
+88
View File
@@ -0,0 +1,88 @@
package base_info
import (
pbOffice "Open_IM/pkg/proto/office"
)
type GetUserTagsReq struct {
OperationID string `json:"operationID" binding:"required"`
}
type GetUserTagsResp struct {
CommResp
Data struct {
Tags []*pbOffice.Tag `json:"tags"`
} `json:"data"`
}
type CreateTagReq struct {
TagName string `json:"tagName" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type CreateTagResp struct {
CommResp
}
type DeleteTagReq struct {
TagID string `json:"tagID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteTagResp struct {
CommResp
}
type SetTagReq struct {
TagID string `json:"tagID" binding:"required"`
NewName string `json:"newName"`
IncreaseUserIDList []string `json:"increaseUserIDList"`
ReduceUserIDList []string `json:"reduceUserIDList"`
OperationID string `json:"operationID" binding:"required"`
}
type SetTagResp struct {
CommResp
}
type SendMsg2TagReq struct {
TagList []string `json:"tagList"`
UserList []string `json:"userList"`
GroupList []string `json:"groupList"`
SenderPlatformID int32 `json:"senderPlatformID" binding:"required"`
Content string `json:"content" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type SendMsg2TagResp struct {
CommResp
}
type GetTagSendLogsReq struct {
PageNumber int32 `json:"pageNumber" binding:"required"`
ShowNumber int32 `json:"showNumber" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetTagSendLogsResp struct {
CommResp
Data struct {
Logs []*pbOffice.TagSendLog `json:"logs"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserTagByIDReq struct {
TagID string `json:"tagID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type GetUserTagByIDResp struct {
CommResp
Data struct {
Tag *pbOffice.Tag `json:"tag"`
} `json:"data"`
}
+110
View File
@@ -0,0 +1,110 @@
package base_info
import open_im_sdk "Open_IM/pkg/proto/sdk_ws"
type CreateDepartmentReq struct {
*open_im_sdk.Department
OperationID string `json:"operationID" binding:"required"`
}
type CreateDepartmentResp struct {
CommResp
Department *open_im_sdk.Department `json:"-"`
Data map[string]interface{} `json:"data"`
}
type UpdateDepartmentReq struct {
*open_im_sdk.Department
DepartmentID string `json:"departmentID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type UpdateDepartmentResp struct {
CommResp
}
type GetSubDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
DepartmentID string `json:"departmentID" binding:"required"`
}
type GetSubDepartmentResp struct {
CommResp
DepartmentList []*open_im_sdk.Department `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type DeleteDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
DepartmentID string `json:"departmentID" binding:"required"`
}
type DeleteDepartmentResp struct {
CommResp
}
type CreateOrganizationUserReq struct {
OperationID string `json:"operationID" binding:"required"`
OrganizationUser *open_im_sdk.OrganizationUser
}
type CreateOrganizationUserResp struct {
CommResp
}
type UpdateOrganizationUserReq struct {
OperationID string `json:"operationID" binding:"required"`
OrganizationUser *open_im_sdk.OrganizationUser
}
type UpdateOrganizationUserResp struct {
CommResp
}
type CreateDepartmentMemberReq struct {
OperationID string `json:"operationID" binding:"required"`
UserInDepartment *open_im_sdk.UserInDepartment
}
type CreateDepartmentMemberResp struct {
CommResp
}
type GetUserInDepartmentReq struct {
UserID string
OperationID string `json:"operationID" binding:"required"`
}
type GetUserInDepartmentResp struct {
CommResp
UserInDepartment *open_im_sdk.UserInDepartment `json:"-"`
Data map[string]interface{} `json:"data"`
}
type UpdateUserInDepartmentReq struct {
OperationID string `json:"operationID" binding:"required"`
*open_im_sdk.DepartmentMember
}
type UpdateUserInDepartmentResp struct {
CommResp
}
type DeleteOrganizationUserReq struct {
UserID string
OperationID string `json:"operationID" binding:"required"`
}
type DeleteOrganizationUserResp struct {
CommResp
}
type GetDepartmentMemberReq struct {
DepartmentID string
OperationID string `json:"operationID" binding:"required"`
}
type GetDepartmentMemberResp struct {
CommResp
UserInDepartmentList []*open_im_sdk.UserInDepartment `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type DeleteUserInDepartmentReq struct {
DepartmentID string `json:"departmentID" binding:"required"`
UserID string `json:"userID" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
}
type DeleteUserInDepartmentResp struct {
CommResp
}
+22
View File
@@ -0,0 +1,22 @@
package base_info
type OSSCredentialReq struct {
OperationID string `json:"operationID"`
Filename string `json:"filename"`
FileType string `json:"file_type"`
}
type OSSCredentialRespData struct {
Endpoint string `json:"endpoint"`
AccessKeyId string `json:"access_key_id"`
AccessKeySecret string `json:"access_key_secret"`
Token string `json:"token"`
Bucket string `json:"bucket"`
FinalHost string `json:"final_host"`
}
type OSSCredentialResp struct {
CommResp
OssData OSSCredentialRespData `json:"-"`
Data map[string]interface{} `json:"data"`
}
+139
View File
@@ -0,0 +1,139 @@
package base_info
import (
"github.com/gin-gonic/gin"
"net/http"
)
type ApiUserInfo struct {
UserID string `json:"userID" binding:"required,min=1,max=64"`
Nickname string `json:"nickname" binding:"omitempty,min=1,max=64"`
FaceURL string `json:"faceURL" binding:"omitempty,max=1024"`
Gender int32 `json:"gender" binding:"omitempty,oneof=0 1 2"`
PhoneNumber string `json:"phoneNumber" binding:"omitempty,max=32"`
Birth uint32 `json:"birth" binding:"omitempty"`
Email string `json:"email" binding:"omitempty,max=64"`
Ex string `json:"ex" binding:"omitempty,max=1024"`
}
//type Conversation struct {
// OwnerUserID string `gorm:"column:owner_user_id;primary_key;type:char(128)" json:"OwnerUserID"`
// ConversationID string `gorm:"column:conversation_id;primary_key;type:char(128)" json:"conversationID"`
// ConversationType int32 `gorm:"column:conversation_type" json:"conversationType"`
// UserID string `gorm:"column:user_id;type:char(64)" json:"userID"`
// GroupID string `gorm:"column:group_id;type:char(128)" json:"groupID"`
// RecvMsgOpt int32 `gorm:"column:recv_msg_opt" json:"recvMsgOpt"`
// UnreadCount int32 `gorm:"column:unread_count" json:"unreadCount"`
// DraftTextTime int64 `gorm:"column:draft_text_time" json:"draftTextTime"`
// IsPinned bool `gorm:"column:is_pinned" json:"isPinned"`
// AttachedInfo string `gorm:"column:attached_info;type:varchar(1024)" json:"attachedInfo"`
// Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
//}
type GroupAddMemberInfo struct {
UserID string `json:"userID" binding:"required"`
RoleLevel int32 `json:"roleLevel" binding:"required"`
}
func SetErrCodeMsg(c *gin.Context, status int) *CommResp {
resp := CommResp{ErrCode: int32(status), ErrMsg: http.StatusText(status)}
c.JSON(status, resp)
return &resp
}
//GroupName string `json:"groupName"`
// Introduction string `json:"introduction"`
// Notification string `json:"notification"`
// FaceUrl string `json:"faceUrl"`
// OperationID string `json:"operationID" binding:"required"`
// GroupType int32 `json:"groupType"`
// Ex string `json:"ex"`
//type GroupInfo struct {
// GroupID string `json:"groupID"`
// GroupName string `json:"groupName"`
// Notification string `json:"notification"`
// Introduction string `json:"introduction"`
// FaceUrl string `json:"faceUrl"`
// OwnerUserID string `json:"ownerUserID"`
// Ex string `json:"ex"`
// GroupType int32 `json:"groupType"`
//}
//type GroupMemberFullInfo struct {
// GroupID string `json:"groupID"`
// UserID string `json:"userID"`
// RoleLevel int32 `json:"roleLevel"`
// JoinTime uint64 `json:"joinTime"`
// Nickname string `json:"nickname"`
// FaceUrl string `json:"faceUrl"`
// FriendRemark string `json:"friendRemark"`
// AppMangerLevel int32 `json:"appMangerLevel"`
// JoinSource int32 `json:"joinSource"`
// OperatorUserID string `json:"operatorUserID"`
// Ex string `json:"ex"`
//}
//
//type PublicUserInfo struct {
// UserID string `json:"userID"`
// Nickname string `json:"nickname"`
// FaceUrl string `json:"faceUrl"`
// Gender int32 `json:"gender"`
//}
//
//type UserInfo struct {
// UserID string `json:"userID"`
// Nickname string `json:"nickname"`
// FaceUrl string `json:"faceUrl"`
// Gender int32 `json:"gender"`
// Mobile string `json:"mobile"`
// Birth string `json:"birth"`
// Email string `json:"email"`
// Ex string `json:"ex"`
//}
//
//type FriendInfo struct {
// OwnerUserID string `json:"ownerUserID"`
// Remark string `json:"remark"`
// CreateTime int64 `json:"createTime"`
// FriendUser UserInfo `json:"friendUser"`
// AddSource int32 `json:"addSource"`
// OperatorUserID string `json:"operatorUserID"`
// Ex string `json:"ex"`
//}
//
//type BlackInfo struct {
// OwnerUserID string `json:"ownerUserID"`
// CreateTime int64 `json:"createTime"`
// BlackUser PublicUserInfo `json:"friendUser"`
// AddSource int32 `json:"addSource"`
// OperatorUserID string `json:"operatorUserID"`
// Ex string `json:"ex"`
//}
//
//type GroupRequest struct {
// UserID string `json:"userID"`
// GroupID string `json:"groupID"`
// HandleResult string `json:"handleResult"`
// ReqMsg string `json:"reqMsg"`
// HandleMsg string `json:"handleMsg"`
// ReqTime int64 `json:"reqTime"`
// HandleUserID string `json:"handleUserID"`
// HandleTime int64 `json:"handleTime"`
// Ex string `json:"ex"`
//}
//
//type FriendRequest struct {
// FromUserID string `json:"fromUserID"`
// ToUserID string `json:"toUserID"`
// HandleResult int32 `json:"handleResult"`
// ReqMessage string `json:"reqMessage"`
// CreateTime int64 `json:"createTime"`
// HandlerUserID string `json:"handlerUserID"`
// HandleMsg string `json:"handleMsg"`
// HandleTime int64 `json:"handleTime"`
// Ex string `json:"ex"`
//}
//
//
//
+34
View File
@@ -0,0 +1,34 @@
package base_info
import (
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
)
type GetUsersInfoReq struct {
OperationID string `json:"operationID" binding:"required"`
UserIDList []string `json:"userIDList" binding:"required"`
}
type GetUsersInfoResp struct {
CommResp
UserInfoList []*open_im_sdk.PublicUserInfo `json:"-"`
Data []map[string]interface{} `json:"data"`
}
type UpdateSelfUserInfoReq struct {
ApiUserInfo
OperationID string `json:"operationID" binding:"required"`
}
type UpdateUserInfoResp struct {
CommResp
}
type GetSelfUserInfoReq struct {
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"userID" binding:"required"`
}
type GetSelfUserInfoResp struct {
CommResp
UserInfo *open_im_sdk.UserInfo `json:"-"`
Data map[string]interface{} `json:"data"`
}
+97
View File
@@ -0,0 +1,97 @@
package base_info
import "Open_IM/pkg/proto/office"
type CreateOneWorkMomentReq struct {
office.CreateOneWorkMomentReq
}
type CreateOneWorkMomentResp struct {
CommResp
}
type DeleteOneWorkMomentReq struct {
office.DeleteOneWorkMomentReq
}
type DeleteOneWorkMomentResp struct {
CommResp
}
type LikeOneWorkMomentReq struct {
office.LikeOneWorkMomentReq
}
type LikeOneWorkMomentResp struct {
CommResp
}
type CommentOneWorkMomentReq struct {
office.CommentOneWorkMomentReq
}
type CommentOneWorkMomentResp struct {
CommResp
}
type WorkMomentsUserCommonReq struct {
PageNumber int32 `json:"pageNumber" binding:"required"`
ShowNumber int32 `json:"showNumber" binding:"required"`
OperationID string `json:"operationID" binding:"required"`
UserID string `json:"UserID" binding:"required"`
}
type GetUserWorkMomentsReq struct {
WorkMomentsUserCommonReq
}
type GetUserWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*office.WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserFriendWorkMomentsReq struct {
WorkMomentsUserCommonReq
}
type GetUserFriendWorkMomentsResp struct {
CommResp
Data struct {
WorkMoments []*office.WorkMoment `json:"workMoments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type GetUserWorkMomentsCommentsMsgReq struct {
WorkMomentsUserCommonReq
}
type GetUserWorkMomentsCommentsMsgResp struct {
CommResp
Data struct {
CommentMsgs []*office.CommentsMsg `json:"comments"`
CurrentPage int32 `json:"currentPage"`
ShowNumber int32 `json:"showNumber"`
} `json:"data"`
}
type SetUserWorkMomentsLevelReq struct {
office.SetUserWorkMomentsLevelReq
}
type SetUserWorkMomentsLevelResp struct {
CommResp
}
type ClearUserWorkMomentsCommentsMsgReq struct {
office.ClearUserWorkMomentsCommentsMsgReq
}
type ClearUserWorkMomentsCommentsMsgResp struct {
CommResp
}
+24
View File
@@ -0,0 +1,24 @@
package call_back_struct
type CommonCallbackReq struct {
SendID string `json:"sendID"`
CallbackCommand string `json:"callbackCommand"`
ServerMsgID string `json:"serverMsgID"`
ClientMsgID string `json:"clientMsgID"`
OperationID string `json:"operationID"`
SenderPlatformID int32 `json:"senderPlatformID"`
SenderNickname string `json:"senderNickname"`
SessionType int32 `json:"sessionType"`
MsgFrom int32 `json:"msgFrom"`
ContentType int32 `json:"contentType"`
Status int32 `json:"status"`
CreateTime int64 `json:"createTime"`
Content string `json:"content"`
}
type CommonCallbackResp struct {
ActionCode int `json:"actionCode"`
ErrCode int `json:"errCode"`
ErrMsg string `json:"errMsg"`
OperationID string `json:"operationID"`
}
+9
View File
@@ -0,0 +1,9 @@
package call_back_struct
type CallbackBeforeCreateGroupReq struct {
CommonCallbackReq
}
type CallbackAfterCreateGroupResp struct {
CommonCallbackResp
}
+47
View File
@@ -0,0 +1,47 @@
package call_back_struct
type CallbackBeforeSendSingleMsgReq struct {
CommonCallbackReq
RecvID string `json:"recvID"`
}
type CallbackBeforeSendSingleMsgResp struct {
CommonCallbackResp
}
type CallbackAfterSendSingleMsgReq struct {
CommonCallbackReq
RecvID string `json:"recvID"`
}
type CallbackAfterSendSingleMsgResp struct {
CommonCallbackResp
}
type CallbackBeforeSendGroupMsgReq struct {
CommonCallbackReq
GroupID string `json:"groupID"`
}
type CallbackBeforeSendGroupMsgResp struct {
CommonCallbackResp
}
type CallbackAfterSendGroupMsgReq struct {
CommonCallbackReq
GroupID string `json:"groupID"`
}
type CallbackAfterSendGroupMsgResp struct {
CommonCallbackResp
}
type CallbackWordFilterReq struct {
CommonCallbackReq
}
type CallbackWordFilterResp struct {
CommonCallbackResp
Content string `json:"content"`
}
+10
View File
@@ -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"`
}
+11
View File
@@ -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"`
}
+144
View File
@@ -0,0 +1,144 @@
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 {
}
+50
View File
@@ -0,0 +1,50 @@
package cms_api_struct
type BroadcastRequest struct {
Message string `json:"message"`
}
type BroadcastResponse struct {
}
type MassSendMassageRequest struct {
Message string `json:"message"`
Users []string `json:"users"`
}
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 string `json:"sender_id"`
SearchContent string `json:"search_content"`
WholeContent string `json:"whole_content"`
ReceiverNickName string `json:"receiver_nick_name,omitempty"`
ReceiverID string `json:"receiver_id,omitempty"`
GroupName string `json:"group_name,omitempty"`
GroupId string `json:"group_id,omitempty"`
Date string `json:"date"`
}
type GetChatLogsResponse struct {
ChatLogs []ChatLog `json:"chat_logs"`
ChatLogsNum int `json:"log_nums"`
ResponsePagination
}
+25
View File
@@ -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"`
}
+89
View File
@@ -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"`
}
+110
View File
@@ -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 {
}
+434
View File
@@ -0,0 +1,434 @@
package config
import (
"io/ioutil"
"os"
"path/filepath"
"runtime"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
var (
_, b, _, _ = runtime.Caller(0)
// Root folder of this project
Root = filepath.Join(filepath.Dir(b), "../../..")
)
var Config config
type callBackConfig struct {
Enable bool `yaml:"enable"`
CallbackTimeOut int `yaml:"callbackTimeOut"`
CallbackFailedContinue bool `yaml:"callbackFailedContinue"`
}
type config struct {
ServerIP string `yaml:"serverip"`
ServerVersion string `yaml:"serverversion"`
Api struct {
GinPort []int `yaml:"openImApiPort"`
}
CmsApi struct {
GinPort []int `yaml:"openImCmsApiPort"`
}
Sdk struct {
WsPort []int `yaml:"openImSdkWsPort"`
}
Credential struct {
Tencent struct {
AppID string `yaml:"appID"`
Region string `yaml:"region"`
Bucket string `yaml:"bucket"`
SecretID string `yaml:"secretID"`
SecretKey string `yaml:"secretKey"`
}
Ali struct {
RegionID string `yaml:"regionID"`
AccessKeyID string `yaml:"accessKeyID"`
AccessKeySecret string `yaml:"accessKeySecret"`
StsEndpoint string `yaml:"stsEndpoint"`
OssEndpoint string `yaml:"ossEndpoint"`
Bucket string `yaml:"bucket"`
FinalHost string `yaml:"finalHost"`
StsDurationSeconds int64 `yaml:"stsDurationSeconds"`
OssRoleArn string `yaml:"OssRoleArn"`
}
Minio struct {
Bucket string `yaml:"bucket"`
Location string `yaml:"location"`
Endpoint string `yaml:"endpoint"`
AccessKeyID string `yaml:"accessKeyID"`
SecretAccessKey string `yaml:"secretAccessKey"`
EndpointInner string `yaml:"endpointInner"`
EndpointInnerEnable bool `yaml:"endpointInnerEnable"`
} `yaml:"minio"`
}
Mysql struct {
DBAddress []string `yaml:"dbMysqlAddress"`
DBUserName string `yaml:"dbMysqlUserName"`
DBPassword string `yaml:"dbMysqlPassword"`
DBDatabaseName string `yaml:"dbMysqlDatabaseName"`
DBTableName string `yaml:"DBTableName"`
DBMsgTableNum int `yaml:"dbMsgTableNum"`
DBMaxOpenConns int `yaml:"dbMaxOpenConns"`
DBMaxIdleConns int `yaml:"dbMaxIdleConns"`
DBMaxLifeTime int `yaml:"dbMaxLifeTime"`
}
Mongo struct {
DBUri string `yaml:"dbUri"` // 当dbUri值不为空则直接使用该值
DBAddress []string `yaml:"dbAddress"`
DBDirect bool `yaml:"dbDirect"`
DBTimeout int `yaml:"dbTimeout"`
DBDatabase string `yaml:"dbDatabase"`
DBSource string `yaml:"dbSource"`
DBUserName string `yaml:"dbUserName"`
DBPassword string `yaml:"dbPassword"`
DBMaxPoolSize int `yaml:"dbMaxPoolSize"`
DBRetainChatRecords int `yaml:"dbRetainChatRecords"`
}
Redis struct {
DBAddress string `yaml:"dbAddress"`
DBMaxIdle int `yaml:"dbMaxIdle"`
DBMaxActive int `yaml:"dbMaxActive"`
DBIdleTimeout int `yaml:"dbIdleTimeout"`
DBPassWord string `yaml:"dbPassWord"`
}
RpcPort struct {
OpenImUserPort []int `yaml:"openImUserPort"`
openImFriendPort []int `yaml:"openImFriendPort"`
RpcMessagePort []int `yaml:"rpcMessagePort"`
RpcPushMessagePort []int `yaml:"rpcPushMessagePort"`
OpenImGroupPort []int `yaml:"openImGroupPort"`
RpcModifyUserInfoPort []int `yaml:"rpcModifyUserInfoPort"`
RpcGetTokenPort []int `yaml:"rpcGetTokenPort"`
}
RpcRegisterName struct {
OpenImStatisticsName string `yaml:"OpenImStatisticsName"`
OpenImUserName string `yaml:"openImUserName"`
OpenImFriendName string `yaml:"openImFriendName"`
OpenImOfflineMessageName string `yaml:"openImOfflineMessageName"`
OpenImPushName string `yaml:"openImPushName"`
OpenImOnlineMessageRelayName string `yaml:"openImOnlineMessageRelayName"`
OpenImGroupName string `yaml:"openImGroupName"`
OpenImAuthName string `yaml:"openImAuthName"`
OpenImMessageCMSName string `yaml:"openImMessageCMSName"`
OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
OpenImOfficeName string `yaml:"openImOfficeName"`
OpenImOrganizationName string `yaml:"openImOrganizationName"`
}
Etcd struct {
EtcdSchema string `yaml:"etcdSchema"`
EtcdAddr []string `yaml:"etcdAddr"`
}
Log struct {
StorageLocation string `yaml:"storageLocation"`
RotationTime int `yaml:"rotationTime"`
RemainRotationCount uint `yaml:"remainRotationCount"`
RemainLogLevel uint `yaml:"remainLogLevel"`
ElasticSearchSwitch bool `yaml:"elasticSearchSwitch"`
ElasticSearchAddr []string `yaml:"elasticSearchAddr"`
ElasticSearchUser string `yaml:"elasticSearchUser"`
ElasticSearchPassword string `yaml:"elasticSearchPassword"`
}
ModuleName struct {
LongConnSvrName string `yaml:"longConnSvrName"`
MsgTransferName string `yaml:"msgTransferName"`
PushName string `yaml:"pushName"`
}
LongConnSvr struct {
WebsocketPort []int `yaml:"openImWsPort"`
WebsocketMaxConnNum int `yaml:"websocketMaxConnNum"`
WebsocketMaxMsgLen int `yaml:"websocketMaxMsgLen"`
WebsocketTimeOut int `yaml:"websocketTimeOut"`
}
Push struct {
Tpns struct {
Ios struct {
AccessID string `yaml:"accessID"`
SecretKey string `yaml:"secretKey"`
}
Android struct {
AccessID string `yaml:"accessID"`
SecretKey string `yaml:"secretKey"`
}
Enable bool `yaml:"enable"`
}
Jpns struct {
AppKey string `yaml:"appKey"`
MasterSecret string `yaml:"masterSecret"`
PushUrl string `yaml:"pushUrl"`
PushIntent string `yaml:"pushIntent"`
Enable bool `yaml:"enable"`
}
Getui struct {
PushUrl string `yaml:"pushUrl"`
AppKey string `yaml:"appKey"`
Enable bool `yaml:"enable"`
Intent string `yaml:"intent"`
MasterSecret string `yaml:"masterSecret"`
}
}
Manager struct {
AppManagerUid []string `yaml:"appManagerUid"`
Secrets []string `yaml:"secrets"`
}
Kafka struct {
Ws2mschat struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
Ms2pschat struct {
Addr []string `yaml:"addr"`
Topic string `yaml:"topic"`
}
ConsumerGroupID struct {
MsgToMongo string `yaml:"msgToMongo"`
MsgToMySql string `yaml:"msgToMySql"`
MsgToPush string `yaml:"msgToPush"`
}
}
Secret string `yaml:"secret"`
MultiLoginPolicy int `yaml:"multiloginpolicy"`
TokenPolicy struct {
AccessSecret string `yaml:"accessSecret"`
AccessExpire int64 `yaml:"accessExpire"`
}
MessageVerify struct {
FriendVerify bool `yaml:"friendVerify"`
}
IOSPush struct {
PushSound string `yaml:"pushSound"`
BadgeCount bool `yaml:"badgeCount"`
}
Callback struct {
CallbackUrl string `yaml:"callbackUrl"`
CallbackBeforeSendSingleMsg callBackConfig `yaml:"callbackbeforeSendSingleMsg"`
CallbackAfterSendSingleMsg callBackConfig `yaml:"callbackAfterSendSingleMsg"`
CallbackBeforeSendGroupMsg callBackConfig `yaml:"callbackBeforeSendGroupMsg"`
CallbackAfterSendGroupMsg callBackConfig `yaml:"callbackAfterSendGroupMsg"`
CallbackWordFilter callBackConfig `yaml:"callbackWordFilter"`
} `yaml:"callback"`
Notification struct {
///////////////////////group/////////////////////////////
GroupCreated struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupCreated"`
GroupInfoSet struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupInfoSet"`
JoinGroupApplication struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"joinGroupApplication"`
MemberQuit struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"memberQuit"`
GroupApplicationAccepted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupApplicationAccepted"`
GroupApplicationRejected struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupApplicationRejected"`
GroupOwnerTransferred struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupOwnerTransferred"`
MemberKicked struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"memberKicked"`
MemberInvited struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"memberInvited"`
MemberEnter struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"memberEnter"`
GroupDismissed struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupDismissed"`
GroupMuted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupMuted"`
GroupCancelMuted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupCancelMuted"`
GroupMemberMuted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupMemberMuted"`
GroupMemberCancelMuted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"groupMemberCancelMuted"`
////////////////////////user///////////////////////
UserInfoUpdated struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"userInfoUpdated"`
//////////////////////friend///////////////////////
FriendApplication struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendApplicationAdded"`
FriendApplicationApproved struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendApplicationApproved"`
FriendApplicationRejected struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendApplicationRejected"`
FriendAdded struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendAdded"`
FriendDeleted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendDeleted"`
FriendRemarkSet struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"friendRemarkSet"`
BlackAdded struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"blackAdded"`
BlackDeleted struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"blackDeleted"`
ConversationOptUpdate struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"conversationOptUpdate"`
ConversationSetPrivate struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips struct {
OpenTips string `yaml:"openTips"`
CloseTips string `yaml:"closeTips"`
} `yaml:"defaultTips"`
} `yaml:"conversationSetPrivate"`
}
Demo struct {
Port []int `yaml:"openImDemoPort"`
AliSMSVerify struct {
AccessKeyID string `yaml:"accessKeyId"`
AccessKeySecret string `yaml:"accessKeySecret"`
SignName string `yaml:"signName"`
VerificationCodeTemplateCode string `yaml:"verificationCodeTemplateCode"`
}
SuperCode string `yaml:"superCode"`
CodeTTL int `yaml:"codeTTL"`
Mail struct {
Title string `yaml:"title"`
SenderMail string `yaml:"senderMail"`
SenderAuthorizationCode string `yaml:"senderAuthorizationCode"`
SmtpAddr string `yaml:"smtpAddr"`
SmtpPort int `yaml:"smtpPort"`
}
}
Rtc struct {
Port int `yaml:"port"`
Address string `yaml:"address"`
} `yaml:"rtc"`
}
type PConversation struct {
ReliabilityLevel int `yaml:"reliabilityLevel"`
UnreadCount bool `yaml:"unreadCount"`
}
type POfflinePush struct {
PushSwitch bool `yaml:"switch"`
Title string `yaml:"title"`
Desc string `yaml:"desc"`
Ext string `yaml:"ext"`
}
type PDefaultTips struct {
Tips string `yaml:"tips"`
}
func init() {
//path, _ := os.Getwd()
//bytes, err := ioutil.ReadFile(path + "/config/config.yaml")
// if we cd Open-IM-Server/src/utils and run go test
// it will panic cannot find config/config.yaml
cfgName := os.Getenv("CONFIG_NAME")
if len(cfgName) == 0 {
cfgName = Root + "/config/config.yaml"
}
viper.SetConfigFile(cfgName)
err := viper.ReadInConfig()
if err != nil {
panic(err.Error())
}
bytes, err := ioutil.ReadFile(cfgName)
if err != nil {
panic(err.Error())
}
if err = yaml.Unmarshal(bytes, &Config); err != nil {
panic(err.Error())
}
}
+235
View File
@@ -0,0 +1,235 @@
package constant
const (
//group admin
// OrdinaryMember = 0
// GroupOwner = 1
// Administrator = 2
//group application
// Application = 0
// AgreeApplication = 1
//friend related
BlackListFlag = 1
ApplicationFriendFlag = 0
FriendFlag = 1
RefuseFriendFlag = -1
//Websocket Protocol
WSGetNewestSeq = 1001
WSPullMsgBySeqList = 1002
WSSendMsg = 1003
WSSendSignalMsg = 1004
WSPushMsg = 2001
WSKickOnlineMsg = 2002
WsLogoutMsg = 2003
WSDataError = 3001
///ContentType
//UserRelated
Text = 101
Picture = 102
Voice = 103
Video = 104
File = 105
AtText = 106
Merger = 107
Card = 108
Location = 109
Custom = 110
Revoke = 111
HasReadReceipt = 112
Typing = 113
Quote = 114
Common = 200
GroupMsg = 201
//SysRelated
NotificationBegin = 1000
FriendApplicationApprovedNotification = 1201 //add_friend_response
FriendApplicationRejectedNotification = 1202 //add_friend_response
FriendApplicationNotification = 1203 //add_friend
FriendAddedNotification = 1204
FriendDeletedNotification = 1205 //delete_friend
FriendRemarkSetNotification = 1206 //set_friend_remark?
BlackAddedNotification = 1207 //add_black
BlackDeletedNotification = 1208 //remove_black
ConversationOptChangeNotification = 1300 // change conversation opt
UserNotificationBegin = 1301
UserInfoUpdatedNotification = 1303 //SetSelfInfoTip = 204
UserNotificationEnd = 1399
OANotification = 1400
GroupNotificationBegin = 1500
GroupCreatedNotification = 1501
GroupInfoSetNotification = 1502
JoinGroupApplicationNotification = 1503
MemberQuitNotification = 1504
GroupApplicationAcceptedNotification = 1505
GroupApplicationRejectedNotification = 1506
GroupOwnerTransferredNotification = 1507
MemberKickedNotification = 1508
MemberInvitedNotification = 1509
MemberEnterNotification = 1510
GroupDismissedNotification = 1511
GroupMemberMutedNotification = 1512
GroupMemberCancelMutedNotification = 1513
GroupMutedNotification = 1514
GroupCancelMutedNotification = 1515
SignalingNotificationBegin = 1600
SignalingNotification = 1601
SignalingNotificationEnd = 1699
ConversationPrivateChatNotification = 1701
NotificationEnd = 2000
//status
MsgNormal = 1
MsgDeleted = 4
//MsgFrom
UserMsgType = 100
SysMsgType = 200
//SessionType
SingleChatType = 1
GroupChatType = 2
NotificationChatType = 4
//token
NormalToken = 0
InValidToken = 1
KickedToken = 2
ExpiredToken = 3
//MultiTerminalLogin
//Full-end login, but the same end is mutually exclusive
AllLoginButSameTermKick = 1
//Only one of the endpoints can log in
SingleTerminalLogin = 2
//The web side can be online at the same time, and the other side can only log in at one end
WebAndOther = 3
//The PC side is mutually exclusive, and the mobile side is mutually exclusive, but the web side can be online at the same time
PcMobileAndWeb = 4
OnlineStatus = "online"
OfflineStatus = "offline"
Registered = "registered"
UnRegistered = "unregistered"
//MsgReceiveOpt
ReceiveMessage = 0
NotReceiveMessage = 1
ReceiveNotNotifyMessage = 2
//OptionsKey
IsHistory = "history"
IsPersistent = "persistent"
IsOfflinePush = "offlinePush"
IsUnreadCount = "unreadCount"
IsConversationUpdate = "conversationUpdate"
IsSenderSync = "senderSync"
IsNotPrivate = "notPrivate"
IsSenderConversationUpdate = "senderConversationUpdate"
//GroupStatus
GroupOk = 0
GroupBanChat = 1
GroupStatusDismissed = 2
GroupStatusMuted = 3
GroupBaned = 3
GroupBanPrivateChat = 4
//UserJoinGroupSource
JoinByAdmin = 1
//Minio
MinioDurationTimes = 3600
// verificationCode used for
VerificationCodeForRegister = 1
VerificationCodeForReset = 2
VerificationCodeForRegisterSuffix = "_forRegister"
VerificationCodeForResetSuffix = "_forReset"
//callbackCommand
CallbackBeforeSendSingleMsgCommand = "callbackBeforeSendSingleMsgCommand"
CallbackAfterSendSingleMsgCommand = "callbackAfterSendSingleMsgCommand"
CallbackBeforeSendGroupMsgCommand = "callbackBeforeSendGroupMsgCommand"
CallbackAfterSendGroupMsgCommand = "callbackAfterSendGroupMsgCommand"
CallbackWordFilterCommand = "callbackWordFilterCommand"
//callback actionCode
ActionAllow = 0
ActionForbidden = 1
//callback callbackHandleCode
CallbackHandleSuccess = 0
CallbackHandleFailed = 1
// minioUpload
OtherType = 1
VideoType = 2
ImageType = 3
)
var ContentType2PushContent = map[int64]string{
Picture: "[图片]",
Voice: "[语音]",
Video: "[视频]",
File: "[文件]",
Text: "你收到了一条文本消息",
AtText: "[有人@你]",
GroupMsg: "你收到一条群聊消息",
Common: "你收到一条新消息",
}
const (
AppOrdinaryUsers = 1
AppAdmin = 2
GroupOrdinaryUsers = 1
GroupOwner = 2
GroupAdmin = 3
GroupResponseAgree = 1
GroupResponseRefuse = -1
FriendResponseAgree = 1
FriendResponseRefuse = -1
Male = 1
Female = 2
)
const (
UnreliableNotification = 1
ReliableNotificationNoMsg = 2
ReliableNotificationMsg = 3
)
const FriendAcceptTip = "You have successfully become friends, so start chatting"
func GroupIsBanChat(status int32) bool {
if status != GroupStatusMuted {
return false
}
return true
}
func GroupIsBanPrivateChat(status int32) bool {
if status != GroupBanPrivateChat {
return false
}
return true
}
const BigVersion = "v3"
const LogFileName = "OpenIM.log"
+100
View File
@@ -0,0 +1,100 @@
package constant
import "errors"
// key = errCode, string = errMsg
type ErrInfo struct {
ErrCode int32
ErrMsg string
}
var (
OK = ErrInfo{0, ""}
ErrServer = ErrInfo{500, "server error"}
// ErrMysql = ErrInfo{100, ""}
// ErrMongo = ErrInfo{110, ""}
// ErrRedis = ErrInfo{120, ""}
ErrParseToken = ErrInfo{700, ParseTokenMsg.Error()}
// ErrCreateToken = ErrInfo{201, "Create token failed"}
// ErrAppServerKey = ErrInfo{300, "key error"}
ErrTencentCredential = ErrInfo{400, ThirdPartyMsg.Error()}
// ErrorUserRegister = ErrInfo{600, "User registration failed"}
// ErrAccountExists = ErrInfo{601, "The account is already registered and cannot be registered again"}
// ErrUserPassword = ErrInfo{602, "User password error"}
// ErrRefreshToken = ErrInfo{605, "Failed to refresh token"}
// ErrAddFriend = ErrInfo{606, "Failed to add friends"}
// ErrAgreeToAddFriend = ErrInfo{607, "Failed to agree application"}
// ErrAddFriendToBlack = ErrInfo{608, "Failed to add friends to the blacklist"}
// ErrGetBlackList = ErrInfo{609, "Failed to get blacklist"}
// ErrDeleteFriend = ErrInfo{610, "Failed to delete friend"}
// ErrGetFriendApplyList = ErrInfo{611, "Failed to get friend application list"}
// ErrGetFriendList = ErrInfo{612, "Failed to get friend list"}
// ErrRemoveBlackList = ErrInfo{613, "Failed to remove blacklist"}
// ErrSearchUserInfo = ErrInfo{614, "Can't find the user information"}
// ErrDelAppleDeviceToken = ErrInfo{615, ""}
// ErrModifyUserInfo = ErrInfo{616, "update user some attribute failed"}
// ErrSetFriendComment = ErrInfo{617, "set friend comment failed"}
// ErrSearchUserInfoFromTheGroup = ErrInfo{618, "There is no such group or the user not in the group"}
// ErrCreateGroup = ErrInfo{619, "create group chat failed"}
// ErrJoinGroupApplication = ErrInfo{620, "Failed to apply to join the group"}
// ErrQuitGroup = ErrInfo{621, "Failed to quit the group"}
// ErrSetGroupInfo = ErrInfo{622, "Failed to set group info"}
// ErrParam = ErrInfo{700, "param failed"}
ErrTokenExpired = ErrInfo{701, TokenExpiredMsg.Error()}
ErrTokenInvalid = ErrInfo{702, TokenInvalidMsg.Error()}
ErrTokenMalformed = ErrInfo{703, TokenMalformedMsg.Error()}
ErrTokenNotValidYet = ErrInfo{704, TokenNotValidYetMsg.Error()}
ErrTokenUnknown = ErrInfo{705, TokenUnknownMsg.Error()}
ErrTokenKicked = ErrInfo{706, TokenUserKickedMsg.Error()}
ErrAccess = ErrInfo{ErrCode: 801, ErrMsg: AccessMsg.Error()}
ErrDB = ErrInfo{ErrCode: 802, ErrMsg: DBMsg.Error()}
ErrArgs = ErrInfo{ErrCode: 8003, ErrMsg: ArgsMsg.Error()}
ErrCallback = ErrInfo{ErrCode: 809, ErrMsg: CallBackMsg.Error()}
)
var (
ParseTokenMsg = errors.New("parse token failed")
TokenExpiredMsg = errors.New("token is timed out, please log in again")
TokenInvalidMsg = errors.New("token has been invalidated")
TokenNotValidYetMsg = errors.New("token not active yet")
TokenMalformedMsg = errors.New("that's not even a token")
TokenUnknownMsg = errors.New("couldn't handle this token")
TokenUserKickedMsg = errors.New("user has been kicked")
AccessMsg = errors.New("no permission")
DBMsg = errors.New("db failed")
ArgsMsg = errors.New("args failed")
CallBackMsg = errors.New("callback failed")
ThirdPartyMsg = errors.New("third party error")
)
const (
NoError = 0
FormattingError = 10001
HasRegistered = 10002
NotRegistered = 10003
PasswordErr = 10004
GetIMTokenErr = 10005
RepeatSendCode = 10006
MailSendCodeErr = 10007
SmsSendCodeErr = 10008
CodeInvalidOrExpired = 10009
RegisterFailed = 10010
ResetPasswordFailed = 10011
DatabaseError = 10002
ServerError = 10004
HttpError = 10005
IoError = 10006
IntentionalError = 10007
)
func (e ErrInfo) Error() string {
return e.ErrMsg
}
func (e *ErrInfo) Code() int32 {
return e.ErrCode
}
@@ -0,0 +1,66 @@
package constant
// fixme 1<--->IOS 2<--->Android 3<--->Windows
//fixme 4<--->OSX 5<--->Web 6<--->MiniWeb 7<--->Linux
const (
//Platform ID
IOSPlatformID = 1
AndroidPlatformID = 2
WindowsPlatformID = 3
OSXPlatformID = 4
WebPlatformID = 5
MiniWebPlatformID = 6
LinuxPlatformID = 7
//Platform string match to Platform ID
IOSPlatformStr = "IOS"
AndroidPlatformStr = "Android"
WindowsPlatformStr = "Windows"
OSXPlatformStr = "OSX"
WebPlatformStr = "Web"
MiniWebPlatformStr = "MiniWeb"
LinuxPlatformStr = "Linux"
//terminal types
TerminalPC = "PC"
TerminalMobile = "Mobile"
)
var PlatformID2Name = map[int32]string{
IOSPlatformID: IOSPlatformStr,
AndroidPlatformID: AndroidPlatformStr,
WindowsPlatformID: WindowsPlatformStr,
OSXPlatformID: OSXPlatformStr,
WebPlatformID: WebPlatformStr,
MiniWebPlatformID: MiniWebPlatformStr,
LinuxPlatformID: LinuxPlatformStr,
}
var PlatformName2ID = map[string]int32{
IOSPlatformStr: IOSPlatformID,
AndroidPlatformStr: AndroidPlatformID,
WindowsPlatformStr: WindowsPlatformID,
OSXPlatformStr: OSXPlatformID,
WebPlatformStr: WebPlatformID,
MiniWebPlatformStr: MiniWebPlatformID,
LinuxPlatformStr: LinuxPlatformID,
}
var Platform2class = map[string]string{
IOSPlatformStr: TerminalMobile,
AndroidPlatformStr: TerminalMobile,
MiniWebPlatformStr: WebPlatformStr,
WebPlatformStr: WebPlatformStr,
WindowsPlatformStr: TerminalPC,
OSXPlatformStr: TerminalPC,
LinuxPlatformStr: TerminalPC,
}
func PlatformIDToName(num int32) string {
return PlatformID2Name[num]
}
func PlatformNameToID(name string) int32 {
return PlatformName2ID[name]
}
func PlatformNameToClass(name string) string {
return Platform2class[name]
}
+119
View File
@@ -0,0 +1,119 @@
package db
import (
"Open_IM/pkg/common/config"
//"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"fmt"
"go.mongodb.org/mongo-driver/mongo/options"
// "context"
// "fmt"
"github.com/garyburd/redigo/redis"
"gopkg.in/mgo.v2"
"time"
"context"
//"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
// "go.mongodb.org/mongo-driver/mongo/options"
)
var DB DataBases
type DataBases struct {
MysqlDB mysqlDB
mgoSession *mgo.Session
redisPool *redis.Pool
mongoClient *mongo.Client
}
func key(dbAddress, dbName string) string {
return dbAddress + "_" + dbName
}
func init() {
//log.NewPrivateLog(constant.LogFileName)
//var mgoSession *mgo.Session
var mongoClient *mongo.Client
var err1 error
//mysql init
initMysqlDB()
// mongo init
// "mongodb://sysop:moon@localhost/records"
uri := "mongodb://sample.host:27017/?maxPoolSize=20&w=majority"
if config.Config.Mongo.DBUri != "" {
// example: mongodb://$user:$password@mongo1.mongo:27017,mongo2.mongo:27017,mongo3.mongo:27017/$DBDatabase/?replicaSet=rs0&readPreference=secondary&authSource=admin&maxPoolSize=$DBMaxPoolSize
uri = config.Config.Mongo.DBUri
} else {
if config.Config.Mongo.DBPassword != "" && config.Config.Mongo.DBUserName != "" {
uri = fmt.Sprintf("mongodb://%s:%s@%s/%s?maxPoolSize=%d", config.Config.Mongo.DBUserName, config.Config.Mongo.DBPassword, config.Config.Mongo.DBAddress[0],
config.Config.Mongo.DBDatabase, config.Config.Mongo.DBMaxPoolSize)
} else {
uri = fmt.Sprintf("mongodb://%s/%s/?maxPoolSize=%d",
config.Config.Mongo.DBAddress[0], config.Config.Mongo.DBDatabase,
config.Config.Mongo.DBMaxPoolSize)
}
}
mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
fmt.Println(" mongo.Connect failed, try ", utils.GetSelfFuncName(), err.Error(), uri)
time.Sleep(time.Duration(30) * time.Second)
mongoClient, err1 = mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err1 != nil {
fmt.Println(" mongo.Connect retry failed, panic", err.Error(), uri)
panic(err1.Error())
}
}
fmt.Println("0", utils.GetSelfFuncName(), "mongo driver client init success: ", uri)
DB.mongoClient = mongoClient
//mgoDailInfo := &mgo.DialInfo{
// Addrs: config.Config.Mongo.DBAddress,
// Direct: config.Config.Mongo.DBDirect,
// Timeout: time.Second * time.Duration(config.Config.Mongo.DBTimeout),
// Database: config.Config.Mongo.DBDatabase,
// Source: config.Config.Mongo.DBSource,
// Username: config.Config.Mongo.DBUserName,
// Password: config.Config.Mongo.DBPassword,
// PoolLimit: config.Config.Mongo.DBMaxPoolSize,
//}
//mgoSession, err = mgo.DialWithInfo(mgoDailInfo)
//
//if err != nil {
//
// mgoSession, err1 = mgo.DialWithInfo(mgoDailInfo)
// if err1 != nil {
// log.NewError(" mongo.Connect failed, panic", err.Error())
// panic(err1.Error())
// }
//}
//DB.mgoSession = mgoSession
//DB.mgoSession.SetMode(mgo.Monotonic, true)
//c := DB.mgoSession.DB(config.Config.Mongo.DBDatabase).C(cChat)
//err = c.EnsureIndexKey("uid")
//if err != nil {
// panic(err.Error())
//}
//
// redis pool init
DB.redisPool = &redis.Pool{
MaxIdle: config.Config.Redis.DBMaxIdle,
MaxActive: config.Config.Redis.DBMaxActive,
IdleTimeout: time.Duration(config.Config.Redis.DBIdleTimeout) * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial(
"tcp",
config.Config.Redis.DBAddress,
redis.DialReadTimeout(time.Duration(1000)*time.Millisecond),
redis.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
redis.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
redis.DialDatabase(0),
redis.DialPassword(config.Config.Redis.DBPassWord),
)
},
}
}
+272
View File
@@ -0,0 +1,272 @@
package db
import "time"
type Register struct {
Account string `gorm:"column:account;primary_key;type:char(255)" json:"account"`
Password string `gorm:"column:password;type:varchar(255)" json:"password"`
Ex string `gorm:"column:ex;size:1024" json:"ex"`
}
//
//message FriendInfo{
//string OwnerUserID = 1;
//string Remark = 2;
//int64 CreateTime = 3;
//UserInfo FriendUser = 4;
//int32 AddSource = 5;
//string OperatorUserID = 6;
//string Ex = 7;
//}
//open_im_sdk.FriendInfo(FriendUser) != imdb.Friend(FriendUserID)
type Friend struct {
OwnerUserID string `gorm:"column:owner_user_id;primary_key;size:64"`
FriendUserID string `gorm:"column:friend_user_id;primary_key;size:64"`
Remark string `gorm:"column:remark;size:255"`
CreateTime time.Time `gorm:"column:create_time"`
AddSource int32 `gorm:"column:add_source"`
OperatorUserID string `gorm:"column:operator_user_id;size:64"`
Ex string `gorm:"column:ex;size:1024"`
}
//message FriendRequest{
//string FromUserID = 1;
//string ToUserID = 2;
//int32 HandleResult = 3;
//string ReqMsg = 4;
//int64 CreateTime = 5;
//string HandlerUserID = 6;
//string HandleMsg = 7;
//int64 HandleTime = 8;
//string Ex = 9;
//}
//open_im_sdk.FriendRequest(nickname, farce url ...) != imdb.FriendRequest
type FriendRequest struct {
FromUserID string `gorm:"column:from_user_id;primary_key;size:64"`
ToUserID string `gorm:"column:to_user_id;primary_key;size:64"`
HandleResult int32 `gorm:"column:handle_result"`
ReqMsg string `gorm:"column:req_msg;size:255"`
CreateTime time.Time `gorm:"column:create_time"`
HandlerUserID string `gorm:"column:handler_user_id;size:64"`
HandleMsg string `gorm:"column:handle_msg;size:255"`
HandleTime time.Time `gorm:"column:handle_time"`
Ex string `gorm:"column:ex;size:1024"`
}
func (FriendRequest) TableName() string {
return "friend_requests"
}
//message GroupInfo{
// string GroupID = 1;
// string GroupName = 2;
// string Notification = 3;
// string Introduction = 4;
// string FaceUrl = 5;
// string OwnerUserID = 6;
// uint32 MemberCount = 8;
// int64 CreateTime = 7;
// string Ex = 9;
// int32 Status = 10;
// string CreatorUserID = 11;
// int32 GroupType = 12;
//}
// open_im_sdk.GroupInfo (OwnerUserID , MemberCount )> imdb.Group
type Group struct {
//`json:"operationID" binding:"required"`
//`protobuf:"bytes,1,opt,name=GroupID" json:"GroupID,omitempty"` `json:"operationID" binding:"required"`
GroupID string `gorm:"column:group_id;primary_key;size:64" json:"groupID" binding:"required"`
GroupName string `gorm:"column:name;size:255" json:"groupName"`
Notification string `gorm:"column:notification;size:255" json:"notification"`
Introduction string `gorm:"column:introduction;size:255" json:"introduction"`
FaceURL string `gorm:"column:face_url;size:255" json:"faceURL"`
CreateTime time.Time `gorm:"column:create_time"`
Ex string `gorm:"column:ex" json:"ex;size:1024" json:"ex"`
Status int32 `gorm:"column:status"`
CreatorUserID string `gorm:"column:creator_user_id;size:64"`
GroupType int32 `gorm:"column:group_type"`
}
//message GroupMemberFullInfo {
//string GroupID = 1 ;
//string UserID = 2 ;
//int32 roleLevel = 3;
//int64 JoinTime = 4;
//string NickName = 5;
//string FaceUrl = 6;
//int32 JoinSource = 8;
//string OperatorUserID = 9;
//string Ex = 10;
//int32 AppMangerLevel = 7; //if >0
//} open_im_sdk.GroupMemberFullInfo(AppMangerLevel) > imdb.GroupMember
type GroupMember struct {
GroupID string `gorm:"column:group_id;primary_key;size:64"`
UserID string `gorm:"column:user_id;primary_key;size:64"`
Nickname string `gorm:"column:nickname;size:255"`
FaceURL string `gorm:"column:user_group_face_url;size:255"`
RoleLevel int32 `gorm:"column:role_level"`
JoinTime time.Time `gorm:"column:join_time"`
JoinSource int32 `gorm:"column:join_source"`
OperatorUserID string `gorm:"column:operator_user_id;size:64"`
MuteEndTime time.Time `gorm:"column:mute_end_time"`
Ex string `gorm:"column:ex;size:1024"`
}
//message GroupRequest{
//string UserID = 1;
//string GroupID = 2;
//string HandleResult = 3;
//string ReqMsg = 4;
//string HandleMsg = 5;
//int64 ReqTime = 6;
//string HandleUserID = 7;
//int64 HandleTime = 8;
//string Ex = 9;
//}open_im_sdk.GroupRequest == imdb.GroupRequest
type GroupRequest struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
GroupID string `gorm:"column:group_id;primary_key;size:64"`
HandleResult int32 `gorm:"column:handle_result"`
ReqMsg string `gorm:"column:req_msg;size:1024"`
HandledMsg string `gorm:"column:handle_msg;size:1024"`
ReqTime time.Time `gorm:"column:req_time"`
HandleUserID string `gorm:"column:handle_user_id;size:64"`
HandledTime time.Time `gorm:"column:handle_time"`
Ex string `gorm:"column:ex;size:1024"`
}
//string UserID = 1;
//string Nickname = 2;
//string FaceUrl = 3;
//int32 Gender = 4;
//string PhoneNumber = 5;
//string Birth = 6;
//string Email = 7;
//string Ex = 8;
//int64 CreateTime = 9;
//int32 AppMangerLevel = 10;
//open_im_sdk.User == imdb.User
type User struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
Nickname string `gorm:"column:name;size:255"`
FaceURL string `gorm:"column:face_url;size:255"`
Gender int32 `gorm:"column:gender"`
PhoneNumber string `gorm:"column:phone_number;size:32"`
Birth time.Time `gorm:"column:birth"`
Email string `gorm:"column:email;size:64"`
Ex string `gorm:"column:ex;size:1024"`
CreateTime time.Time `gorm:"column:create_time"`
AppMangerLevel int32 `gorm:"column:app_manger_level"`
}
//message BlackInfo{
//string OwnerUserID = 1;
//int64 CreateTime = 2;
//PublicUserInfo BlackUserInfo = 4;
//int32 AddSource = 5;
//string OperatorUserID = 6;
//string Ex = 7;
//}
// open_im_sdk.BlackInfo(BlackUserInfo) != imdb.Black (BlockUserID)
type Black struct {
OwnerUserID string `gorm:"column:owner_user_id;primary_key;size:64"`
BlockUserID string `gorm:"column:block_user_id;primary_key;size:64"`
CreateTime time.Time `gorm:"column:create_time"`
AddSource int32 `gorm:"column:add_source"`
OperatorUserID string `gorm:"column:operator_user_id;size:64"`
Ex string `gorm:"column:ex;size:1024"`
}
type ChatLog struct {
ServerMsgID string `gorm:"column:server_msg_id;primary_key;type:char(64)" json:"serverMsgID"`
ClientMsgID string `gorm:"column:client_msg_id;type:char(64)" json:"clientMsgID"`
SendID string `gorm:"column:send_id;type:char(64)" json:"sendID"`
RecvID string `gorm:"column:recv_id;type:char(64)" json:"recvID"`
SenderPlatformID int32 `gorm:"column:sender_platform_id" json:"senderPlatformID"`
SenderNickname string `gorm:"column:sender_nick_name;type:varchar(255)" json:"senderNickname"`
SenderFaceURL string `gorm:"column:sender_face_url;type:varchar(255)" json:"senderFaceURL"`
SessionType int32 `gorm:"column:session_type" json:"sessionType"`
MsgFrom int32 `gorm:"column:msg_from" json:"msgFrom"`
ContentType int32 `gorm:"column:content_type" json:"contentType"`
Content string `gorm:"column:content;type:varchar(3000)" json:"content"`
Status int32 `gorm:"column:status" json:"status"`
SendTime time.Time `gorm:"column:send_time" json:"sendTime"`
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (ChatLog) TableName() string {
return "chat_logs"
}
type BlackList struct {
UserId string `gorm:"column:uid"`
BeginDisableTime time.Time `gorm:"column:begin_disable_time"`
EndDisableTime time.Time `gorm:"column:end_disable_time"`
}
type Conversation struct {
OwnerUserID string `gorm:"column:owner_user_id;primary_key;type:char(128)" json:"OwnerUserID"`
ConversationID string `gorm:"column:conversation_id;primary_key;type:char(128)" json:"conversationID"`
ConversationType int32 `gorm:"column:conversation_type" json:"conversationType"`
UserID string `gorm:"column:user_id;type:char(64)" json:"userID"`
GroupID string `gorm:"column:group_id;type:char(128)" json:"groupID"`
RecvMsgOpt int32 `gorm:"column:recv_msg_opt" json:"recvMsgOpt"`
UnreadCount int32 `gorm:"column:unread_count" json:"unreadCount"`
DraftTextTime int64 `gorm:"column:draft_text_time" json:"draftTextTime"`
IsPinned bool `gorm:"column:is_pinned" json:"isPinned"`
IsPrivateChat bool `gorm:"column:is_private_chat" json:"isPrivateChat"`
AttachedInfo string `gorm:"column:attached_info;type:varchar(1024)" json:"attachedInfo"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (Conversation) TableName() string {
return "conversations"
}
type Department struct {
DepartmentID string `gorm:"column:department_id;primary_key;size:64" json:"departmentID"`
FaceURL string `gorm:"column:face_url;size:255" json:"faceURL"`
Name string `gorm:"column:name;size:256" json:"name" binding:"required"`
ParentID string `gorm:"column:parent_id;size:64" json:"parentID" binding:"required"` // "0" or Real parent id
Order int32 `gorm:"column:order" json:"order" ` // 1, 2, ...
DepartmentType int32 `gorm:"column:department_type" json:"departmentType"` //1, 2...
CreateTime time.Time `gorm:"column:create_time" json:"createTime"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (Department) TableName() string {
return "departments"
}
type OrganizationUser struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
Nickname string `gorm:"column:nickname;size:256"`
EnglishName string `gorm:"column:english_name;size:256"`
FaceURL string `gorm:"column:face_url;size:256"`
Gender int32 `gorm:"column:gender"` //1 ,2
Mobile string `gorm:"column:mobile;size:32"`
Telephone string `gorm:"column:telephone;size:32"`
Birth time.Time `gorm:"column:birth"`
Email string `gorm:"column:email;size:64"`
CreateTime time.Time `gorm:"column:create_time"`
Ex string `gorm:"column:ex;size:1024"`
}
func (OrganizationUser) TableName() string {
return "organization_users"
}
type DepartmentMember struct {
UserID string `gorm:"column:user_id;primary_key;size:64"`
DepartmentID string `gorm:"column:department_id;primary_key;size:64"`
Order int32 `gorm:"column:order" json:"order"` //1,2
Position string `gorm:"column:position;size:256" json:"position"`
Leader int32 `gorm:"column:leader" json:"leader"` //-1, 1
Status int32 `gorm:"column:status" json:"status"` //-1, 1
CreateTime time.Time `gorm:"column:create_time"`
Ex string `gorm:"column:ex;type:varchar(1024)" json:"ex"`
}
func (DepartmentMember) TableName() string {
return "department_members"
}
+681
View File
@@ -0,0 +1,681 @@
package db
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/log"
pbMsg "Open_IM/pkg/proto/chat"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"context"
"errors"
"fmt"
"github.com/gogo/protobuf/sortkeys"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
//"github.com/garyburd/redigo/redis"
"github.com/golang/protobuf/proto"
"gopkg.in/mgo.v2/bson"
"strconv"
"time"
)
const cChat = "msg"
const cGroup = "group"
const cTag = "tag"
const cSendLog = "send_log"
const singleGocMsgNum = 5000
type MsgInfo struct {
SendTime int64
Msg []byte
}
type UserChat struct {
UID string
Msg []MsgInfo
}
type GroupMember_x struct {
GroupID string
UIDList []string
}
func (d *DataBases) GetMinSeqFromMongo(uid string) (MinSeq uint32, err error) {
return 1, nil
//var i, NB uint32
//var seqUid string
//session := d.mgoSession.Clone()
//if session == nil {
// return MinSeq, errors.New("session == nil")
//}
//defer session.Close()
//c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
//MaxSeq, err := d.GetUserMaxSeq(uid)
//if err != nil && err != redis.ErrNil {
// return MinSeq, err
//}
//NB = uint32(MaxSeq / singleGocMsgNum)
//for i = 0; i <= NB; i++ {
// seqUid = indexGen(uid, i)
// n, err := c.Find(bson.M{"uid": seqUid}).Count()
// if err == nil && n != 0 {
// if i == 0 {
// MinSeq = 1
// } else {
// MinSeq = uint32(i * singleGocMsgNum)
// }
// break
// }
//}
//return MinSeq, nil
}
func (d *DataBases) GetMinSeqFromMongo2(uid string) (MinSeq uint32, err error) {
return 1, nil
}
// deleteMsgByLogic
func (d *DataBases) DelMsgLogic(uid string, seqList []uint32, operationID string) error {
sortkeys.Uint32s(seqList)
seqMsgs, err := d.GetMsgBySeqListMongo2(uid, seqList, operationID)
if err != nil {
return utils.Wrap(err, "")
}
for _, seqMsg := range seqMsgs {
log.NewDebug(operationID, utils.GetSelfFuncName(), *seqMsg)
seqMsg.Status = constant.MsgDeleted
if err = d.ReplaceMsgBySeq(uid, seqMsg, operationID); err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "ReplaceMsgListBySeq error", err.Error())
}
}
return nil
}
func (d *DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
uid = getSeqUid(uid, msg.Seq)
seqIndex := getMsgIndex(msg.Seq)
s := fmt.Sprintf("msg.%d.msg", seqIndex)
log.NewDebug(operationID, utils.GetSelfFuncName(), seqIndex, s)
bytes, err := proto.Marshal(msg)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "proto marshal", err.Error())
return utils.Wrap(err, "")
}
updateResult, err := c.UpdateOne(
ctx, bson.M{"uid": uid},
bson.M{"$set": bson.M{s: bytes}})
log.NewInfo(operationID, utils.GetSelfFuncName(), updateResult)
if err != nil {
log.NewError(operationID, utils.GetSelfFuncName(), "UpdateOne", err.Error())
return utils.Wrap(err, "")
}
return nil
}
func (d *DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, seqList)
var hasSeqList []uint32
singleCount := 0
session := d.mgoSession.Clone()
if session == nil {
return nil, errors.New("session == nil")
}
defer session.Close()
c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
m := func(uid string, seqList []uint32) map[string][]uint32 {
t := make(map[string][]uint32)
for i := 0; i < len(seqList); i++ {
seqUid := getSeqUid(uid, seqList[i])
if value, ok := t[seqUid]; !ok {
var temp []uint32
t[seqUid] = append(temp, seqList[i])
} else {
t[seqUid] = append(value, seqList[i])
}
}
return t
}(uid, seqList)
sChat := UserChat{}
for seqUid, value := range m {
if err = c.Find(bson.M{"uid": seqUid}).One(&sChat); err != nil {
log.NewError(operationID, "not find seqUid", seqUid, value, uid, seqList, err.Error())
continue
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
}
if isContainInt32(msg.Seq, value) {
seqMsg = append(seqMsg, msg)
hasSeqList = append(hasSeqList, msg.Seq)
singleCount++
if singleCount == len(value) {
break
}
}
}
}
if len(hasSeqList) != len(seqList) {
var diff []uint32
diff = utils.Difference(hasSeqList, seqList)
exceptionMSg := genExceptionMessageBySeqList(diff)
seqMsg = append(seqMsg, exceptionMSg...)
}
return seqMsg, nil
}
func (d *DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
var hasSeqList []uint32
singleCount := 0
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
m := func(uid string, seqList []uint32) map[string][]uint32 {
t := make(map[string][]uint32)
for i := 0; i < len(seqList); i++ {
seqUid := getSeqUid(uid, seqList[i])
if value, ok := t[seqUid]; !ok {
var temp []uint32
t[seqUid] = append(temp, seqList[i])
} else {
t[seqUid] = append(value, seqList[i])
}
}
return t
}(uid, seqList)
sChat := UserChat{}
for seqUid, value := range m {
if err = c.FindOne(ctx, bson.M{"uid": seqUid}).Decode(&sChat); err != nil {
log.NewError(operationID, "not find seqUid", seqUid, value, uid, seqList, err.Error())
continue
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
}
if isContainInt32(msg.Seq, value) {
seqMsg = append(seqMsg, msg)
hasSeqList = append(hasSeqList, msg.Seq)
singleCount++
if singleCount == len(value) {
break
}
}
}
}
if len(hasSeqList) != len(seqList) {
var diff []uint32
diff = utils.Difference(hasSeqList, seqList)
exceptionMSg := genExceptionMessageBySeqList(diff)
seqMsg = append(seqMsg, exceptionMSg...)
}
return seqMsg, nil
}
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
msg.Seq = v
exceptionMsg = append(exceptionMsg, msg)
}
return exceptionMsg
}
func (d *DataBases) SaveUserChatMongo2(uid string, sendTime int64, m *pbMsg.MsgDataToDB) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
newTime := getCurrentTimestampByMill()
operationID := ""
seqUid := getSeqUid(uid, m.MsgData.Seq)
filter := bson.M{"uid": seqUid}
var err error
sMsg := MsgInfo{}
sMsg.SendTime = sendTime
if sMsg.Msg, err = proto.Marshal(m.MsgData); err != nil {
return utils.Wrap(err, "")
}
err = c.FindOneAndUpdate(ctx, filter, bson.M{"$push": bson.M{"msg": sMsg}}).Err()
log.NewDebug(operationID, "get mgoSession cost time", getCurrentTimestampByMill()-newTime)
if err != nil {
sChat := UserChat{}
sChat.UID = seqUid
sChat.Msg = append(sChat.Msg, sMsg)
if _, err = c.InsertOne(ctx, &sChat); err != nil {
log.NewDebug(operationID, "InsertOne failed", filter)
return utils.Wrap(err, "")
}
} else {
log.NewDebug(operationID, "FindOneAndUpdate ok", filter)
}
log.NewDebug(operationID, "find mgo uid cost time", getCurrentTimestampByMill()-newTime)
return nil
}
func (d *DataBases) SaveUserChat(uid string, sendTime int64, m *pbMsg.MsgDataToDB) error {
var seqUid string
newTime := getCurrentTimestampByMill()
session := d.mgoSession.Clone()
if session == nil {
return errors.New("session == nil")
}
defer session.Close()
log.NewDebug("", "get mgoSession cost time", getCurrentTimestampByMill()-newTime)
c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
seqUid = getSeqUid(uid, m.MsgData.Seq)
n, err := c.Find(bson.M{"uid": seqUid}).Count()
if err != nil {
return err
}
log.NewDebug("", "find mgo uid cost time", getCurrentTimestampByMill()-newTime)
sMsg := MsgInfo{}
sMsg.SendTime = sendTime
if sMsg.Msg, err = proto.Marshal(m.MsgData); err != nil {
return err
}
if n == 0 {
sChat := UserChat{}
sChat.UID = seqUid
sChat.Msg = append(sChat.Msg, sMsg)
err = c.Insert(&sChat)
if err != nil {
return err
}
} else {
err = c.Update(bson.M{"uid": seqUid}, bson.M{"$push": bson.M{"msg": sMsg}})
if err != nil {
return err
}
}
log.NewDebug("", "insert mgo data cost time", getCurrentTimestampByMill()-newTime)
return nil
}
func (d *DataBases) DelUserChat(uid string) error {
return nil
//session := d.mgoSession.Clone()
//if session == nil {
// return errors.New("session == nil")
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
//
//delTime := time.Now().Unix() - int64(config.Config.Mongo.DBRetainChatRecords)*24*3600
//if err := c.Update(bson.M{"uid": uid}, bson.M{"$pull": bson.M{"msg": bson.M{"sendtime": bson.M{"$lte": delTime}}}}); err != nil {
// return err
//}
//
//return nil
}
func (d *DataBases) DelUserChatMongo2(uid string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
filter := bson.M{"uid": uid}
delTime := time.Now().Unix() - int64(config.Config.Mongo.DBRetainChatRecords)*24*3600
if _, err := c.UpdateOne(ctx, filter, bson.M{"$pull": bson.M{"msg": bson.M{"sendtime": bson.M{"$lte": delTime}}}}); err != nil {
return utils.Wrap(err, "")
}
return nil
}
func (d *DataBases) MgoUserCount() (int, error) {
return 0, nil
//session := d.mgoSession.Clone()
//if session == nil {
// return 0, errors.New("session == nil")
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
//
//return c.Find(nil).Count()
}
func (d *DataBases) MgoSkipUID(count int) (string, error) {
return "", nil
//session := d.mgoSession.Clone()
//if session == nil {
// return "", errors.New("session == nil")
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cChat)
//
//sChat := UserChat{}
//c.Find(nil).Skip(count).Limit(1).One(&sChat)
//return sChat.UID, nil
}
func (d *DataBases) GetGroupMember(groupID string) []string {
return nil
//groupInfo := GroupMember_x{}
//groupInfo.GroupID = groupID
//groupInfo.UIDList = make([]string, 0)
//
//session := d.mgoSession.Clone()
//if session == nil {
// return groupInfo.UIDList
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cGroup)
//
//if err := c.Find(bson.M{"groupid": groupInfo.GroupID}).One(&groupInfo); err != nil {
// return groupInfo.UIDList
//}
//
//return groupInfo.UIDList
}
func (d *DataBases) AddGroupMember(groupID, uid string) error {
return nil
//session := d.mgoSession.Clone()
//if session == nil {
// return errors.New("session == nil")
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cGroup)
//
//n, err := c.Find(bson.M{"groupid": groupID}).Count()
//if err != nil {
// return err
//}
//
//if n == 0 {
// groupInfo := GroupMember_x{}
// groupInfo.GroupID = groupID
// groupInfo.UIDList = append(groupInfo.UIDList, uid)
// err = c.Insert(&groupInfo)
// if err != nil {
// return err
// }
//} else {
// err = c.Update(bson.M{"groupid": groupID}, bson.M{"$addToSet": bson.M{"uidlist": uid}})
// if err != nil {
// return err
// }
//}
//
//return nil
}
func (d *DataBases) DelGroupMember(groupID, uid string) error {
return nil
//session := d.mgoSession.Clone()
//if session == nil {
// return errors.New("session == nil")
//}
//defer session.Close()
//
//c := session.DB(config.Config.Mongo.DBDatabase).C(cGroup)
//
//if err := c.Update(bson.M{"groupid": groupID}, bson.M{"$pull": bson.M{"uidlist": uid}}); err != nil {
// return err
//}
//
//return nil
}
type Tag struct {
UserID string `bson:"user_id"`
TagID string `bson:"tag_id"`
TagName string `bson:"tag_name"`
UserList []string `bson:"user_list"`
}
func (d *DataBases) GetUserTags(userID string) ([]Tag, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
var tags []Tag
cursor, err := c.Find(ctx, bson.M{"user_id": userID})
if err != nil {
return tags, err
}
if err = cursor.All(ctx, &tags); err != nil {
return tags, err
}
return tags, nil
}
func (d *DataBases) CreateTag(userID, tagName string, userList []string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
tagID := generateTagID(tagName, userID)
tag := Tag{
UserID: userID,
TagID: tagID,
TagName: tagName,
UserList: userList,
}
_, err := c.InsertOne(ctx, tag)
return err
}
func (d *DataBases) GetTagByID(userID, tagID string) (Tag, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
var tag Tag
err := c.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag, err
}
func (d *DataBases) DeleteTag(userID, tagID string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
_, err := c.DeleteOne(ctx, bson.M{"user_id": userID, "tag_id": tagID})
return err
}
func (d *DataBases) SetTag(userID, tagID, newName string, increaseUserIDList []string, reduceUserIDList []string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
var tag Tag
if err := c.FindOne(ctx, bson.M{"tag_id": tagID, "user_id": userID}).Decode(&tag); err != nil {
return err
}
if newName != "" {
_, err := c.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"tag_name": newName}})
if err != nil {
return err
}
}
tag.UserList = append(tag.UserList, increaseUserIDList...)
tag.UserList = utils.RemoveRepeatedStringInList(tag.UserList)
for _, v := range reduceUserIDList {
for i2, v2 := range tag.UserList {
if v == v2 {
tag.UserList[i2] = ""
}
}
}
var newUserList []string
for _, v := range tag.UserList {
if v != "" {
newUserList = append(newUserList, v)
}
}
_, err := c.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"user_list": newUserList}})
if err != nil {
return err
}
return nil
}
func (d *DataBases) GetUserIDListByTagID(userID, tagID string) ([]string, error) {
var tag Tag
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cTag)
_ = c.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag.UserList, nil
}
type TagUser struct {
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
}
type TagSendLog struct {
UserList []TagUser `bson:"tag_list"`
SendID string `bson:"send_id"`
SenderPlatformID int32 `bson:"sender_platform_id"`
Content string `bson:"content"`
SendTime int64 `bson:"send_time"`
}
func (d *DataBases) SaveTagSendLog(tagSendLog *TagSendLog) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cSendLog)
_, err := c.InsertOne(ctx, tagSendLog)
return err
}
func (d *DataBases) GetTagSendLogs(userID string, showNumber, pageNumber int32) ([]TagSendLog, error) {
var tagSendLogs []TagSendLog
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cSendLog)
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"send_time": -1})
cursor, err := c.Find(ctx, bson.M{"send_id": userID}, findOpts)
if err != nil {
return tagSendLogs, err
}
err = cursor.All(ctx, &tagSendLogs)
if err != nil {
return tagSendLogs, err
}
return tagSendLogs, nil
}
type WorkMoment struct {
WorkMomentID string `bson:"work_moment_id"`
UserID string `bson:"user_id"`
Content string `bson:"content"`
LikeUsers []*LikeUser `bson:"like_users"`
Comments []*Comment `bson:"comments"`
WhoCanSeeUserIDList []string `bson:"who_can_see_user_id_list"`
WhoCantSeeUserIDList []string `bson:"who_cant_see_user_id_list"`
IsPrivate bool
IsPublic bool
CreateTime int32
}
type LikeUser struct {
UserID string
UserName string
}
type Comment struct {
UserID string
UserName string
ReplyUserID string
ReplyUserName string
ContentID string
Content string
CreateTime int32
}
func (d *DataBases) CreateOneWorkMoment(workMoment *WorkMoment) error {
return nil
}
func (d *DataBases) DeleteOneWorkMoment(workMomentID string) error {
return nil
}
func (d *DataBases) GetWorkMomentByID(workMomentID string) (*WorkMoment, error) {
return nil, nil
}
func (d *DataBases) LikeOneWorkMoment(likeUserID, workMomentID string) error {
return nil
}
func (d *DataBases) SetUserWorkMomentsLevel(userID string, level int32) error {
return nil
}
func (d *DataBases) ClearUserWorkMomentsCommentsMsg(userID string) error {
return nil
}
type CommentMsg struct {
WorkMomentID string `bson:"workMoment"`
CommentContent string `bson:"content"`
Comment
}
func (d *DataBases) GetUserWorkMomentsCommentsMsg(userID string, showNumber, pageNumber int32) ([]CommentMsg, error) {
return nil, nil
}
func (d *DataBases) CommentOneWorkMoment(comment Comment, workMomentID string) error {
return nil
}
func (d *DataBases) GetUserWorkMoments(userID string, showNumber, pageNumber int32) ([]WorkMoment, error) {
return nil, nil
}
func (d *DataBases) GetUserFriendWorkMoments(friendIDList []string, showNumber, pageNumber int32) ([]WorkMoment, error) {
return nil, nil
}
func generateTagID(tagName, userID string) string {
return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func generateWorkMomentID(userID string) string {
return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func getCurrentTimestampByMill() int64 {
return time.Now().UnixNano() / 1e6
}
func getSeqUid(uid string, seq uint32) string {
seqSuffix := seq / singleGocMsgNum
return indexGen(uid, seqSuffix)
}
func getMsgIndex(seq uint32) int {
seqSuffix := seq / singleGocMsgNum
var index uint32
if seqSuffix == 0 {
index = (seq - seqSuffix*5000) - 1
} else {
index = seq - seqSuffix*singleGocMsgNum
}
return int(index)
}
func isContainInt32(target uint32, List []uint32) bool {
for _, element := range List {
if target == element {
return true
}
}
return false
}
func indexGen(uid string, seqSuffix uint32) string {
return uid + ":" + strconv.FormatInt(int64(seqSuffix), 10)
}
+162
View File
@@ -0,0 +1,162 @@
package db
import (
"Open_IM/pkg/common/config"
"fmt"
"sync"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type mysqlDB struct {
sync.RWMutex
dbMap map[string]*gorm.DB
}
func initMysqlDB() {
//When there is no open IM database, connect to the mysql built-in database to create openIM database
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], "mysql")
var db *gorm.DB
var err1 error
db, err := gorm.Open("mysql", dsn)
if err != nil {
fmt.Println("0", "Open failed ", err.Error(), dsn)
}
if err != nil {
time.Sleep(time.Duration(30) * time.Second)
db, err1 = gorm.Open("mysql", dsn)
if err1 != nil {
fmt.Println("0", "Open failed ", err1.Error(), dsn)
panic(err1.Error())
}
}
//Check the database and table during initialization
sql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8 COLLATE utf8_general_ci;", config.Config.Mysql.DBDatabaseName)
err = db.Exec(sql).Error
if err != nil {
fmt.Println("0", "Exec failed ", err.Error(), sql)
panic(err.Error())
}
db.Close()
dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], config.Config.Mysql.DBDatabaseName)
db, err = gorm.Open("mysql", dsn)
if err != nil {
fmt.Println("0", "Open failed ", err.Error(), dsn)
panic(err.Error())
}
fmt.Println("open db ok ", dsn)
db.AutoMigrate(&Friend{},
&FriendRequest{},
&Group{},
&GroupMember{},
&GroupRequest{},
&User{},
&Black{}, &ChatLog{}, &Register{}, &Conversation{})
db.Set("gorm:table_options", "CHARSET=utf8")
db.Set("gorm:table_options", "collation=utf8_unicode_ci")
if !db.HasTable(&Friend{}) {
fmt.Println("CreateTable Friend")
db.CreateTable(&Friend{})
}
if !db.HasTable(&FriendRequest{}) {
fmt.Println("CreateTable FriendRequest")
db.CreateTable(&FriendRequest{})
}
if !db.HasTable(&Group{}) {
fmt.Println("CreateTable Group")
db.CreateTable(&Group{})
}
if !db.HasTable(&GroupMember{}) {
fmt.Println("CreateTable GroupMember")
db.CreateTable(&GroupMember{})
}
if !db.HasTable(&GroupRequest{}) {
fmt.Println("CreateTable GroupRequest")
db.CreateTable(&GroupRequest{})
}
if !db.HasTable(&User{}) {
fmt.Println("CreateTable User")
db.CreateTable(&User{})
}
if !db.HasTable(&Black{}) {
fmt.Println("CreateTable Black")
db.CreateTable(&Black{})
}
if !db.HasTable(&ChatLog{}) {
fmt.Println("CreateTable ChatLog")
db.CreateTable(&ChatLog{})
}
if !db.HasTable(&Register{}) {
fmt.Println("CreateTable Register")
db.CreateTable(&Register{})
}
if !db.HasTable(&Conversation{}) {
fmt.Println("CreateTable Conversation")
db.CreateTable(&Conversation{})
}
if !db.HasTable(&Department{}) {
fmt.Println("CreateTable Department")
db.CreateTable(&Department{})
}
if !db.HasTable(&OrganizationUser{}) {
fmt.Println("CreateTable OrganizationUser")
db.CreateTable(&OrganizationUser{})
}
if !db.HasTable(&DepartmentMember{}) {
fmt.Println("CreateTable DepartmentMember")
db.CreateTable(&DepartmentMember{})
}
return
}
func (m *mysqlDB) DefaultGormDB() (*gorm.DB, error) {
return m.GormDB(config.Config.Mysql.DBAddress[0], config.Config.Mysql.DBDatabaseName)
}
func (m *mysqlDB) GormDB(dbAddress, dbName string) (*gorm.DB, error) {
m.Lock()
defer m.Unlock()
k := key(dbAddress, dbName)
if _, ok := m.dbMap[k]; !ok {
if err := m.open(dbAddress, dbName); err != nil {
return nil, err
}
}
return m.dbMap[k], nil
}
func (m *mysqlDB) open(dbAddress, dbName string) error {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, dbAddress, dbName)
db, err := gorm.Open("mysql", dsn)
if err != nil {
return err
}
db.SingularTable(true)
db.DB().SetMaxOpenConns(config.Config.Mysql.DBMaxOpenConns)
db.DB().SetMaxIdleConns(config.Config.Mysql.DBMaxIdleConns)
db.DB().SetConnMaxLifetime(time.Duration(config.Config.Mysql.DBMaxLifeTime) * time.Second)
if m.dbMap == nil {
m.dbMap = make(map[string]*gorm.DB)
}
k := key(dbAddress, dbName)
m.dbMap[k] = db
return nil
}
@@ -0,0 +1,41 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
_ "github.com/jinzhu/gorm"
)
func GetRegister(account string) (*db.Register, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var r db.Register
return &r, dbConn.Table("registers").Where("account = ?",
account).Take(&r).Error
}
func SetPassword(account, password, ex string) error {
r := db.Register{
Account: account,
Password: password,
Ex: ex,
}
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Table("registers").Create(&r).Error
}
func ResetPassword(account, password string) error {
r := db.Register{
Password: password,
}
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
dbConn.LogMode(false)
if err != nil {
return err
}
return dbConn.Table("registers").Where("account = ?", account).Update(&r).Error
}
@@ -0,0 +1,91 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
_ "github.com/jinzhu/gorm/dialects/mysql"
"time"
)
func InsertToFriend(toInsertFollow *db.Friend) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
toInsertFollow.CreateTime = time.Now()
err = dbConn.Table("friends").Create(toInsertFollow).Error
if err != nil {
return err
}
return nil
}
func GetFriendRelationshipFromFriend(OwnerUserID, FriendUserID string) (*db.Friend, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var friend db.Friend
err = dbConn.Table("friends").Where("owner_user_id=? and friend_user_id=?", OwnerUserID, FriendUserID).Take(&friend).Error
if err != nil {
return nil, err
}
return &friend, err
}
func GetFriendListByUserID(OwnerUserID string) ([]db.Friend, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var friends []db.Friend
var x db.Friend
x.OwnerUserID = OwnerUserID
err = dbConn.Table("friends").Where("owner_user_id=?", OwnerUserID).Find(&friends).Error
if err != nil {
return nil, err
}
return friends, nil
}
func GetFriendIDListByUserID(OwnerUserID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var friendIDList []string
err = dbConn.Table("friends").Select("friend_user_id").Where("owner_user_id=?", OwnerUserID).Find(&friendIDList).Error
if err != nil {
return nil, err
}
return friendIDList, nil
}
func UpdateFriendComment(OwnerUserID, FriendUserID, Remark string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Exec("update friends set remark=? where owner_user_id=? and friend_user_id=?", Remark, OwnerUserID, FriendUserID).Error
return err
}
func DeleteSingleFriendInfo(OwnerUserID, FriendUserID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("friends").Where("owner_user_id=? and friend_user_id=?", OwnerUserID, FriendUserID).Delete(db.Friend{}).Error
return err
}
//type Friend struct {
// OwnerUserID string `gorm:"column:owner_user_id;primaryKey;"`
// FriendUserID string `gorm:"column:friend_user_id;primaryKey;"`
// Remark string `gorm:"column:remark"`
// CreateTime time.Time `gorm:"column:create_time"`
// AddSource int32 `gorm:"column:add_source"`
// OperatorUserID string `gorm:"column:operator_user_id"`
// Ex string `gorm:"column:ex"`
//}
@@ -0,0 +1,112 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"time"
)
//type FriendRequest struct {
// FromUserID string `gorm:"column:from_user_id;primaryKey;"`
// ToUserID string `gorm:"column:to_user_id;primaryKey;"`
// HandleResult int32 `gorm:"column:handle_result"`
// ReqMessage string `gorm:"column:req_message"`
// CreateTime time.Time `gorm:"column:create_time"`
// HandlerUserID string `gorm:"column:handler_user_id"`
// HandleMsg string `gorm:"column:handle_msg"`
// HandleTime time.Time `gorm:"column:handle_time"`
// Ex string `gorm:"column:ex"`
//}
// who apply to add me
func GetReceivedFriendsApplicationListByUserID(ToUserID string) ([]db.FriendRequest, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var usersInfo []db.FriendRequest
err = dbConn.Table("friend_requests").Where("to_user_id=?", ToUserID).Find(&usersInfo).Error
if err != nil {
return nil, err
}
return usersInfo, nil
}
//I apply to add somebody
func GetSendFriendApplicationListByUserID(FromUserID string) ([]db.FriendRequest, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var usersInfo []db.FriendRequest
err = dbConn.Table("friend_requests").Where("from_user_id=?", FromUserID).Find(&usersInfo).Error
if err != nil {
return nil, err
}
return usersInfo, nil
}
//FromUserId apply to add ToUserID
func GetFriendApplicationByBothUserID(FromUserID, ToUserID string) (*db.FriendRequest, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var friendRequest db.FriendRequest
err = dbConn.Table("friend_requests").Where("from_user_id=? and to_user_id=?", FromUserID, ToUserID).Take(&friendRequest).Error
if err != nil {
return nil, err
}
return &friendRequest, nil
}
func UpdateFriendApplication(friendRequest *db.FriendRequest) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
friendRequest.CreateTime = time.Now()
return dbConn.Table("friend_requests").Where("from_user_id=? and to_user_id=?",
friendRequest.FromUserID, friendRequest.ToUserID).Update(&friendRequest).Error
}
func InsertFriendApplication(friendRequest *db.FriendRequest, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if err = dbConn.Table("friend_requests").Create(friendRequest).Error; err == nil {
return nil
}
//t := dbConn.Debug().Table("friend_requests").Where("from_user_id = ? and to_user_id = ?", friendRequest.FromUserID, friendRequest.ToUserID).Select("*").Updates(*friendRequest)
//if t.RowsAffected == 0 {
// return utils.Wrap(errors.New("RowsAffected == 0"), "no update")
//}
//return utils.Wrap(t.Error, "")
friendRequest.CreateTime = time.Now()
args["create_time"] = friendRequest.CreateTime
u := dbConn.Model(friendRequest).Updates(args)
//u := dbConn.Table("friend_requests").Where("from_user_id=? and to_user_id=?",
// friendRequest.FromUserID, friendRequest.ToUserID).Update(&friendRequest)
//u := dbConn.Table("friend_requests").Where("from_user_id=? and to_user_id=?",
// friendRequest.FromUserID, friendRequest.ToUserID).Update(&friendRequest)
if u.RowsAffected != 0 {
return nil
}
if friendRequest.CreateTime.Unix() < 0 {
friendRequest.CreateTime = time.Now()
}
if friendRequest.HandleTime.Unix() < 0 {
friendRequest.HandleTime = utils.UnixSecondToTime(0)
}
err = dbConn.Table("friend_requests").Create(friendRequest).Error
if err != nil {
return err
}
return nil
}
@@ -0,0 +1,316 @@
package im_mysql_model
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"errors"
"fmt"
"time"
)
//type GroupMember struct {
// GroupID string `gorm:"column:group_id;primaryKey;"`
// UserID string `gorm:"column:user_id;primaryKey;"`
// NickName string `gorm:"column:nickname"`
// FaceUrl string `gorm:"user_group_face_url"`
// RoleLevel int32 `gorm:"column:role_level"`
// JoinTime time.Time `gorm:"column:join_time"`
// JoinSource int32 `gorm:"column:join_source"`
// OperatorUserID string `gorm:"column:operator_user_id"`
// Ex string `gorm:"column:ex"`
//}
func InsertIntoGroupMember(toInsertInfo db.GroupMember) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
toInsertInfo.JoinTime = time.Now()
if toInsertInfo.RoleLevel == 0 {
toInsertInfo.RoleLevel = constant.GroupOrdinaryUsers
}
toInsertInfo.MuteEndTime = time.Unix(int64(time.Now().Second()), 0)
err = dbConn.Table("group_members").Create(toInsertInfo).Error
if err != nil {
return err
}
return nil
}
func GetGroupMemberListByUserID(userID string) ([]db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupMemberList []db.GroupMember
err = dbConn.Table("group_members").Where("user_id=?", userID).Find(&groupMemberList).Error
//err = dbConn.Table("group_members").Where("user_id=?", userID).Take(&groupMemberList).Error
if err != nil {
return nil, err
}
return groupMemberList, nil
}
func GetGroupMemberListByGroupID(groupID string) ([]db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupMemberList []db.GroupMember
err = dbConn.Table("group_members").Where("group_id=?", groupID).Find(&groupMemberList).Error
if err != nil {
return nil, err
}
return groupMemberList, nil
}
func GetGroupMemberIDListByGroupID(groupID string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
dbConn.LogMode(false)
var groupMembers []db.GroupMember
err = dbConn.Table("group_members").Select("user_id").Where("group_id=?", groupID).Find(&groupMembers).Error
if err != nil {
return nil, err
}
var groupMemberIDList []string
for _, v := range groupMembers {
groupMemberIDList = append(groupMemberIDList, v.UserID)
}
return groupMemberIDList, nil
}
func GetGroupMemberListByGroupIDAndRoleLevel(groupID string, roleLevel int32) ([]db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupMemberList []db.GroupMember
err = dbConn.Table("group_members").Where("group_id=? and role_level=?", groupID, roleLevel).Find(&groupMemberList).Error
if err != nil {
return nil, err
}
return groupMemberList, nil
}
func GetGroupMemberInfoByGroupIDAndUserID(groupID, userID string) (*db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupMember db.GroupMember
err = dbConn.Table("group_members").Where("group_id=? and user_id=? ", groupID, userID).Limit(1).Take(&groupMember).Error
if err != nil {
return nil, err
}
return &groupMember, nil
}
func DeleteGroupMemberByGroupIDAndUserID(groupID, userID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("group_members").Where("group_id=? and user_id=? ", groupID, userID).Delete(db.GroupMember{}).Error
if err != nil {
return err
}
return nil
}
func DeleteGroupMemberByGroupID(groupID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("group_members").Where("group_id=? ", groupID).Delete(db.GroupMember{}).Error
if err != nil {
return err
}
return nil
}
func UpdateGroupMemberInfo(groupMemberInfo db.GroupMember) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("group_members").Where("group_id=? and user_id=?", groupMemberInfo.GroupID, groupMemberInfo.UserID).Update(&groupMemberInfo).Error
if err != nil {
return err
}
return nil
}
func GetOwnerManagerByGroupID(groupID string) ([]db.GroupMember, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupMemberList []db.GroupMember
err = dbConn.Table("group_members").Where("group_id=? and role_level>?", groupID, constant.GroupOrdinaryUsers).Find(&groupMemberList).Error
if err != nil {
return nil, err
}
return groupMemberList, nil
}
func GetGroupMemberNumByGroupID(groupID string) (uint32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, utils.Wrap(err, "DefaultGormDB failed")
}
var number uint32
err = dbConn.Table("group_members").Where("group_id=?", groupID).Count(&number).Error
if err != nil {
return 0, utils.Wrap(err, "")
}
return number, nil
}
func GetGroupOwnerInfoByGroupID(groupID string) (*db.GroupMember, error) {
omList, err := GetOwnerManagerByGroupID(groupID)
if err != nil {
return nil, err
}
for _, v := range omList {
if v.RoleLevel == constant.GroupOwner {
return &v, nil
}
}
return nil, utils.Wrap(errors.New("no owner"), "")
}
func IsExistGroupMember(groupID, userID string) bool {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return false
}
var number int32
err = dbConn.Table("group_members").Where("group_id = ? and user_id = ?", groupID, userID).Count(&number).Error
if err != nil {
return false
}
if number != 1 {
return false
}
return true
}
func RemoveGroupMember(groupID string, UserID string) error {
return DeleteGroupMemberByGroupIDAndUserID(groupID, UserID)
}
func GetMemberInfoByID(groupID string, userID string) (*db.GroupMember, error) {
return GetGroupMemberInfoByGroupIDAndUserID(groupID, userID)
}
func GetGroupMemberByGroupID(groupID string, filter int32, begin int32, maxNumber int32) ([]db.GroupMember, error) {
var memberList []db.GroupMember
var err error
if filter >= 0 {
memberList, err = GetGroupMemberListByGroupIDAndRoleLevel(groupID, filter) //sorted by join time
} else {
memberList, err = GetGroupMemberListByGroupID(groupID)
}
if err != nil {
return nil, err
}
if begin >= int32(len(memberList)) {
return nil, nil
}
var end int32
if begin+int32(maxNumber) < int32(len(memberList)) {
end = begin + maxNumber
} else {
end = int32(len(memberList))
}
return memberList[begin:end], nil
}
func GetJoinedGroupIDListByUserID(userID string) ([]string, error) {
memberList, err := GetGroupMemberListByUserID(userID)
if err != nil {
return nil, err
}
var groupIDList []string = make([]string, len(memberList))
for _, v := range memberList {
groupIDList = append(groupIDList, v.GroupID)
}
return groupIDList, nil
}
func IsGroupOwnerAdmin(groupID, UserID string) bool {
groupMemberList, err := GetOwnerManagerByGroupID(groupID)
if err != nil {
return false
}
for _, v := range groupMemberList {
if v.UserID == UserID && v.RoleLevel > constant.GroupOrdinaryUsers {
return true
}
}
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(false)
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 UpdateGroupMemberInfoDefaultZero(groupMemberInfo db.GroupMember, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Model(groupMemberInfo).Updates(args).Error
}
//
//func SelectGroupList(groupID string) ([]string, error) {
// var groupUserID string
// var groupList []string
// dbConn, err := db.DB.MysqlDB.DefaultGormDB()
// if err != nil {
// return groupList, err
// }
//
// rows, err := dbConn.Model(&GroupMember{}).Where("group_id = ?", groupID).Select("user_id").Rows()
// if err != nil {
// return groupList, err
// }
// defer rows.Close()
// for rows.Next() {
// rows.Scan(&groupUserID)
// groupList = append(groupList, groupUserID)
// }
// return groupList, nil
//}
@@ -0,0 +1,225 @@
package im_mysql_model
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"errors"
"fmt"
"github.com/jinzhu/gorm"
"time"
)
//type Group struct {
// GroupID string `gorm:"column:group_id;primaryKey;"`
// GroupName string `gorm:"column:name"`
// Introduction string `gorm:"column:introduction"`
// Notification string `gorm:"column:notification"`
// FaceUrl string `gorm:"column:face_url"`
// CreateTime time.Time `gorm:"column:create_time"`
// Status int32 `gorm:"column:status"`
// CreatorUserID string `gorm:"column:creator_user_id"`
// GroupType int32 `gorm:"column:group_type"`
// Ex string `gorm:"column:ex"`
//}
func InsertIntoGroup(groupInfo db.Group) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if groupInfo.GroupName == "" {
groupInfo.GroupName = "Group Chat"
}
groupInfo.CreateTime = time.Now()
err = dbConn.Table("groups").Create(groupInfo).Error
if err != nil {
return err
}
return nil
}
func GetGroupInfoByGroupID(groupId string) (*db.Group, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, utils.Wrap(err, "")
}
var groupInfo db.Group
err = dbConn.Table("groups").Where("group_id=?", groupId).Take(&groupInfo).Error
if err != nil {
return nil, err
}
return &groupInfo, nil
}
func SetGroupInfo(groupInfo db.Group) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
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
}
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
}
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
}
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) (string, string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return "", "", err
}
groupMember := db.GroupMember{
UserID: userId,
GroupID: groupId,
}
updateInfo := db.GroupMember{
RoleLevel: roleLevel,
}
groupMaster := db.GroupMember{}
switch roleLevel {
case constant.GroupOwner:
err = dbConn.Transaction(func(tx *gorm.DB) error {
result := dbConn.Table("group_members").Where("group_id = ? and role_level = ?", groupId, constant.GroupOwner).First(&groupMaster).Update(&db.GroupMember{
RoleLevel: constant.GroupOrdinaryUsers,
})
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))
}
result = dbConn.Table("group_members").First(&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
})
case constant.GroupOrdinaryUsers:
err = dbConn.Transaction(func(tx *gorm.DB) error {
result := dbConn.Table("group_members").Where("group_id = ? and role_level = ?", groupId, constant.GroupOwner).First(&groupMaster)
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))
}
if groupMaster.UserID == userId {
return errors.New(fmt.Sprintf("user %s is master of %s, cant set to ordinary user", userId, groupId))
} else {
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
})
}
return "", "", nil
}
func GetGroupsCountNum(group db.Group) (int32, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0, err
}
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
}
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
}
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
}
func UpdateGroupInfoDefaultZero(groupID string, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Table("groups").Where("group_id = ? ", groupID).Update(args).Error
}
@@ -0,0 +1,209 @@
package im_mysql_model
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"time"
)
//type GroupRequest struct {
// UserID string `gorm:"column:user_id;primaryKey;"`
// GroupID string `gorm:"column:group_id;primaryKey;"`
// HandleResult int32 `gorm:"column:handle_result"`
// ReqMsg string `gorm:"column:req_msg"`
// HandledMsg string `gorm:"column:handled_msg"`
// ReqTime time.Time `gorm:"column:req_time"`
// HandleUserID string `gorm:"column:handle_user_id"`
// HandledTime time.Time `gorm:"column:handle_time"`
// Ex string `gorm:"column:ex"`
//}
func UpdateGroupRequest(groupRequest db.GroupRequest) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if groupRequest.HandledTime.Unix() < 0 {
groupRequest.HandledTime = utils.UnixSecondToTime(0)
}
return dbConn.Table("group_requests").Where("group_id=? and user_id=?", groupRequest.GroupID, groupRequest.UserID).Update(&groupRequest).Error
}
func InsertIntoGroupRequest(toInsertInfo db.GroupRequest) error {
DelGroupRequestByGroupIDAndUserID(toInsertInfo.GroupID, toInsertInfo.UserID)
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if toInsertInfo.HandledTime.Unix() < 0 {
toInsertInfo.HandledTime = utils.UnixSecondToTime(0)
}
u := dbConn.Table("group_requests").Where("group_id=? and user_id=?", toInsertInfo.GroupID, toInsertInfo.UserID).Update(&toInsertInfo)
if u.RowsAffected != 0 {
return nil
}
toInsertInfo.ReqTime = time.Now()
if toInsertInfo.HandledTime.Unix() < 0 {
toInsertInfo.HandledTime = utils.UnixSecondToTime(0)
}
err = dbConn.Table("group_requests").Create(&toInsertInfo).Error
if err != nil {
return err
}
return nil
}
func GetGroupRequestByGroupIDAndUserID(groupID, userID string) (*db.GroupRequest, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupRequest db.GroupRequest
err = dbConn.Table("group_requests").Where("user_id=? and group_id=?", userID, groupID).Take(&groupRequest).Error
if err != nil {
return nil, err
}
return &groupRequest, nil
}
func DelGroupRequestByGroupIDAndUserID(groupID, userID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("group_requests").Where("group_id=? and user_id=?", groupID, userID).Delete(db.GroupRequest{}).Error
if err != nil {
return err
}
return nil
}
func GetGroupRequestByGroupID(groupID string) ([]db.GroupRequest, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var groupRequestList []db.GroupRequest
err = dbConn.Table("group_requests").Where("group_id=?", groupID).Find(&groupRequestList).Error
if err != nil {
return nil, err
}
return groupRequestList, nil
}
//received
func GetGroupApplicationList(userID string) ([]db.GroupRequest, error) {
var groupRequestList []db.GroupRequest
memberList, err := GetGroupMemberListByUserID(userID)
if err != nil {
return nil, err
}
for _, v := range memberList {
if v.RoleLevel > constant.GroupOrdinaryUsers {
list, err := GetGroupRequestByGroupID(v.GroupID)
if err != nil {
// fmt.Println("111 GetGroupRequestByGroupID failed ", err.Error())
continue
}
// fmt.Println("222 GetGroupRequestByGroupID ok ", list)
groupRequestList = append(groupRequestList, list...)
// fmt.Println("333 GetGroupRequestByGroupID ok ", groupRequestList)
}
}
return groupRequestList, nil
}
func GetUserReqGroupByUserID(userID string) ([]db.GroupRequest, error) {
var groupRequestList []db.GroupRequest
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
dbConn.LogMode(false)
err = dbConn.Table("group_requests").Where("user_id=?", userID).Find(&groupRequestList).Error
return groupRequestList, err
}
//
//func GroupApplicationResponse(pb *group.GroupApplicationResponseReq) (*group.CommonResp, error) {
//
// ownerUser, err := FindGroupMemberInfoByGroupIdAndUserId(pb.GroupID, pb.OwnerID)
// if err != nil {
// log.ErrorByKv("FindGroupMemberInfoByGroupIdAndUserId failed", pb.OperationID, "groupId", pb.GroupID, "ownerID", pb.OwnerID)
// return nil, err
// }
// if ownerUser.AdministratorLevel <= 0 {
// return nil, errors.New("insufficient permissions")
// }
//
// dbConn, err := db.DB.MysqlDB.DefaultGormDB()
// if err != nil {
// return nil, err
// }
// var groupRequest GroupRequest
// err = dbConn.Raw("select * from `group_request` where handled_user = ? and group_id = ? and from_user_id = ? and to_user_id = ?",
// "", pb.GroupID, pb.FromUserID, pb.ToUserID).Scan(&groupRequest).Error
// if err != nil {
// log.ErrorByKv("find group_request info failed", pb.OperationID, "groupId", pb.GroupID, "fromUserId", pb.FromUserID, "toUserId", pb.OwnerID)
// return nil, err
// }
//
// if groupRequest.Flag != 0 {
// return nil, errors.New("application has already handle")
// }
//
// var saveFlag int
// if pb.HandleResult == 0 {
// saveFlag = -1
// } else if pb.HandleResult == 1 {
// saveFlag = 1
// } else {
// return nil, errors.New("parma HandleResult error")
// }
// err = dbConn.Exec("update `group_request` set flag = ?, handled_msg = ?, handled_user = ? where group_id = ? and from_user_id = ? and to_user_id = ?",
// saveFlag, pb.HandledMsg, pb.OwnerID, groupRequest.GroupID, groupRequest.FromUserID, groupRequest.ToUserID).Error
// if err != nil {
// log.ErrorByKv("update group request failed", pb.OperationID, "groupID", pb.GroupID, "flag", saveFlag, "ownerId", pb.OwnerID, "fromUserId", pb.FromUserID, "toUserID", pb.ToUserID)
// return nil, err
// }
//
// if saveFlag == 1 {
// if groupRequest.ToUserID == "0" {
// err = InsertIntoGroupMember(pb.GroupID, pb.FromUserID, groupRequest.FromUserNickname, groupRequest.FromUserFaceUrl, 0)
// if err != nil {
// log.ErrorByKv("InsertIntoGroupMember failed", pb.OperationID, "groupID", pb.GroupID, "fromUserId", pb.FromUserID)
// return nil, err
// }
// } else {
// err = InsertIntoGroupMember(pb.GroupID, pb.ToUserID, groupRequest.ToUserNickname, groupRequest.ToUserFaceUrl, 0)
// if err != nil {
// log.ErrorByKv("InsertIntoGroupMember failed", pb.OperationID, "groupID", pb.GroupID, "fromUserId", pb.FromUserID)
// return nil, err
// }
// }
// }
//
// return &group.GroupApplicationResponseResp{}, nil
//}
//func FindGroupBeInvitedRequestInfoByUidAndGroupID(groupId, uid string) (*GroupRequest, error) {
// dbConn, err := db.DB.MysqlDB.DefaultGormDB()
// if err != nil {
// return nil, err
// }
// var beInvitedRequestUserInfo GroupRequest
// err = dbConn.Table("group_request").Where("to_user_id=? and group_id=?", uid, groupId).Find(&beInvitedRequestUserInfo).Error
// if err != nil {
// return nil, err
// }
// return &beInvitedRequestUserInfo, nil
//
//}
//func InsertGroupRequest(groupId, fromUser, fromUserNickName, fromUserFaceUrl, toUser, requestMsg, handledMsg string, handleStatus int) error {
// return nil
//}
@@ -0,0 +1,68 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"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(false)
db := dbConn.Table("chat_logs").
Where(fmt.Sprintf(" content like '%%%s%%'", chatLog.Content)).
Limit(showNumber).Offset(showNumber * (pageNumber - 1))
if chatLog.SessionType != 0 {
db = db.Where("session_type = ?", chatLog.SessionType)
}
if chatLog.ContentType != 0 {
db = db.Where("content_type = ?", chatLog.ContentType)
}
if chatLog.SendID != "" {
db = db.Where("send_id = ?", chatLog.SendID)
}
if chatLog.RecvID != "" {
db = db.Where("recv_id = ?", chatLog.RecvID)
}
if chatLog.SendTime.Unix() > 0 {
db = db.Where("send_time > ? and send_time < ?", chatLog.SendTime, chatLog.SendTime.AddDate(0, 0, 1))
}
err = db.Find(&chatLogs).Error
return chatLogs, err
}
func GetChatLogCount(chatLog db.ChatLog) (int64, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
var chatLogs []db.ChatLog
var count int64
if err != nil {
return count, err
}
dbConn.LogMode(false)
db := dbConn.Table("chat_logs").
Where(fmt.Sprintf(" content like '%%%s%%'", chatLog.Content))
if chatLog.SessionType != 0 {
db = db.Where("session_type = ?", chatLog.SessionType)
}
if chatLog.ContentType != 0 {
db = db.Where("content_type = ?", chatLog.ContentType)
}
if chatLog.SendID != "" {
db = db.Where("send_id = ?", chatLog.SendID)
}
if chatLog.RecvID != "" {
db = db.Where("recv_id = ?", chatLog.RecvID)
}
if chatLog.SendTime.Unix() > 0 {
log.NewDebug("", utils.GetSelfFuncName(), chatLog.SendTime, chatLog.SendTime.AddDate(0, 0, 1))
db = db.Where("send_time > ? and send_time < ?", chatLog.SendTime, chatLog.SendTime.AddDate(0, 0, 1))
}
err = db.Find(&chatLogs).Count(&count).Error
return count, err
}
@@ -0,0 +1,182 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"time"
)
func CreateDepartment(department *db.Department) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
department.CreateTime = time.Now()
return dbConn.Table("departments").Create(department).Error
}
func GetDepartment(departmentID string) (error, *db.Department) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err, nil
}
var department db.Department
err = dbConn.Table("departments").Where("department_id=?", departmentID).Find(&department).Error
return err, &department
}
func UpdateDepartment(department *db.Department, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if err = dbConn.Table("departments").Where("department_id=?", department.DepartmentID).Updates(department).Error; err != nil {
return err
}
if args != nil {
return dbConn.Table("departments").Where("department_id=?", department.DepartmentID).Updates(args).Error
}
return nil
}
func GetSubDepartmentList(departmentID string) (error, []db.Department) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err, nil
}
var departmentList []db.Department
err = dbConn.Table("departments").Where("parent_id=?", departmentID).Find(&departmentList).Error
return err, departmentList
}
func DeleteDepartment(departmentID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if err = dbConn.Table("departments").Where("department_id=?", departmentID).Delete(db.Department{}).Error; err != nil {
return err
}
if err = dbConn.Table("department_members").Where("department_id=?", departmentID).Delete(db.DepartmentMember{}).Error; err != nil {
return err
}
return nil
}
func CreateOrganizationUser(organizationUser *db.OrganizationUser) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
organizationUser.CreateTime = time.Now()
return dbConn.Table("organization_users").Create(organizationUser).Error
}
func GetOrganizationUser(userID string) (error, *db.OrganizationUser) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err, nil
}
organizationUser := db.OrganizationUser{}
err = dbConn.Table("organization_users").Where("user_id=?", userID).Take(&organizationUser).Error
return err, &organizationUser
}
func UpdateOrganizationUser(organizationUser *db.OrganizationUser, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if err = dbConn.Table("organization_users").Where("user_id=?", organizationUser.UserID).Updates(organizationUser).Error; err != nil {
return err
}
if args != nil {
return dbConn.Table("organization_users").Where("user_id=?", organizationUser.UserID).Updates(args).Error
}
return nil
}
func CreateDepartmentMember(departmentMember *db.DepartmentMember) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
departmentMember.CreateTime = time.Now()
return dbConn.Table("department_members").Create(departmentMember).Error
}
func GetUserInDepartment(userID string) (error, []db.DepartmentMember) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err, nil
}
var departmentMemberList []db.DepartmentMember
err = dbConn.Table("department_members").Where("user_id=?", userID).Take(&departmentMemberList).Error
return err, departmentMemberList
}
func UpdateUserInDepartment(departmentMember *db.DepartmentMember, args map[string]interface{}) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
if err = dbConn.Table("department_members").Where("department_id=? ADN user_id=?", departmentMember.DepartmentID, departmentMember.UserID).
Updates(departmentMember).Error; err != nil {
return err
}
if args != nil {
return dbConn.Table("department_members").Where("department_id=? ADN user_id=?", departmentMember.DepartmentID, departmentMember.UserID).
Updates(args).Error
}
return nil
}
func DeleteUserInDepartment(departmentID, userID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Table("department_members").Where("department_id=? ADN user_id=?", departmentID, userID).Delete(db.DepartmentMember{}).Error
}
func DeleteUserInAllDepartment(userID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Table("department_members").Where("user_id=?", userID).Delete(db.DepartmentMember{}).Error
}
func DeleteOrganizationUser(OrganizationUserID string) error {
if err := DeleteUserInAllDepartment(OrganizationUserID); err != nil {
return err
}
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
return dbConn.Table("organization_users").Where("user_id=?", OrganizationUserID).Delete(db.OrganizationUser{}).Error
}
func GetDepartmentMemberUserIDList(departmentID string) (error, []string) {
//dbConn, err := db.DB.MysqlDB.DefaultGormDB()
//if err != nil {
// return err
//}
//return dbConn.Table("department_members").Where("user_id=?", userID).Delete(db.DepartmentMember{}).Error
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err, nil
}
var departmentMemberList []db.DepartmentMember
err = dbConn.Table("department_members").Where("department_id=?", departmentID).Take(&departmentMemberList).Error
if err != nil {
return err, nil
}
var userIDList []string = make([]string, 0)
for _, v := range departmentMemberList {
userIDList = append(userIDList, v.UserID)
}
return err, userIDList
}
@@ -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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
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.Table("groups").Where("group_id= ? ", group.GroupID).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(false)
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
}
@@ -0,0 +1,58 @@
package im_mysql_model
import (
"Open_IM/pkg/common/db"
"Open_IM/pkg/utils"
"time"
)
func InsertInToUserBlackList(black db.Black) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
black.CreateTime = time.Now()
err = dbConn.Table("blacks").Create(black).Error
return err
}
//type Black struct {
// OwnerUserID string `gorm:"column:owner_user_id;primaryKey;"`
// BlockUserID string `gorm:"column:block_user_id;primaryKey;"`
// CreateTime time.Time `gorm:"column:create_time"`
// AddSource int32 `gorm:"column:add_source"`
// OperatorUserID int32 `gorm:"column:operator_user_id"`
// Ex string `gorm:"column:ex"`
//}
func CheckBlack(ownerUserID, blockUserID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
var black db.Black
err = dbConn.Table("blacks").Where("owner_user_id=? and block_user_id=?", ownerUserID, blockUserID).Find(&black).Error
return err
}
func RemoveBlackList(ownerUserID, blockUserID string) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
err = dbConn.Table("blacks").Where("owner_user_id=? and block_user_id=?", ownerUserID, blockUserID).Delete(db.Black{}).Error
return utils.Wrap(err, "RemoveBlackList failed")
}
func GetBlackListByUserID(ownerUserID string) ([]db.Black, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var blackListUsersInfo []db.Black
err = dbConn.Table("blacks").Where("owner_user_id=?", ownerUserID).Find(&blackListUsersInfo).Error
if err != nil {
return nil, err
}
return blackListUsersInfo, nil
}
@@ -0,0 +1,398 @@
package im_mysql_model
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"fmt"
"time"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func init() {
//init managers
for k, v := range config.Config.Manager.AppManagerUid {
user, err := GetUserByUserID(v)
if err != nil {
fmt.Println("GetUserByUserID failed ", err.Error(), v, user)
} else {
continue
}
var appMgr db.User
appMgr.UserID = v
appMgr.Nickname = "AppManager" + utils.IntToString(k+1)
appMgr.AppMangerLevel = constant.AppAdmin
err = UserRegister(appMgr)
if err != nil {
fmt.Println("AppManager insert error", err.Error(), appMgr, "time: ", appMgr.Birth.Unix())
}
}
}
func UserRegister(user db.User) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
user.CreateTime = time.Now()
if user.AppMangerLevel == 0 {
user.AppMangerLevel = constant.AppOrdinaryUsers
}
if user.Birth.Unix() < 0 {
user.Birth = utils.UnixSecondToTime(0)
}
err = dbConn.Table("users").Create(&user).Error
if err != nil {
return err
}
return nil
}
func DeleteUser(userID string) (i int64) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return 0
}
i = dbConn.Table("users").Where("user_id=?", userID).Delete(db.User{}).RowsAffected
return i
}
func GetUserByUserID(userID string) (*db.User, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var user db.User
err = dbConn.Table("users").Where("user_id=?", userID).Take(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
func GetUserNameByUserID(userID string) (string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return "", err
}
var user db.User
err = dbConn.Table("users").Select("name").Where("user_id=?", userID).First(&user).Error
if err != nil {
return "", err
}
return user.Nickname, nil
}
func UpdateUserInfo(user db.User) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
err = dbConn.Table("users").Where("user_id=?", user.UserID).Update(&user).Error
return err
}
func SelectAllUserID() ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return nil, err
}
var resultArr []string
err = dbConn.Table("users").Pluck("user_id", &resultArr).Error
if err != nil {
return nil, err
}
return resultArr, nil
}
func SelectSomeUserID(userIDList []string) ([]string, error) {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
dbConn.LogMode(false)
if err != nil {
return nil, err
}
var resultArr []string
err = dbConn.Table("users").Where("user_id IN (?) ", userIDList).Pluck("user_id", &resultArr).Error
if err != nil {
return nil, err
}
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(false)
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(false)
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(false)
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(false)
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(false)
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(false)
var count int32
if err := dbConn.Model(&db.BlackList{}).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func SetConversation(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
} else {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"recv_msg_opt": conversation.RecvMsgOpt, "is_pinned": conversation.IsPinned, "is_private_chat": conversation.IsPrivateChat}).Error
}
}
func PeerUserSetConversation(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
}
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"is_private_chat": conversation.IsPrivateChat}).Error
}
func SetRecvMsgOpt(conversation db.Conversation) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
dbConn.LogMode(false)
newConversation := conversation
if dbConn.Model(&db.Conversation{}).Find(&newConversation).RowsAffected == 0 {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "not exist in db, create")
return dbConn.Model(&db.Conversation{}).Create(conversation).Error
// if exist, then update record
} else {
log.NewDebug("", utils.GetSelfFuncName(), "conversation", conversation, "exist in db, update")
//force update
return dbConn.Model(conversation).Where("owner_user_id = ? and conversation_id = ?", conversation.OwnerUserID, conversation.ConversationID).
Update(map[string]interface{}{"recv_msg_opt": conversation.RecvMsgOpt}).Error
}
}
func GetUserAllConversations(ownerUserID string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
dbConn.LogMode(false)
err = dbConn.Model(&db.Conversation{}).Where("owner_user_id=?", ownerUserID).Find(&conversations).Error
return conversations, err
}
func GetConversation(OwnerUserID, conversationID string) (db.Conversation, error) {
var conversation db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversation, err
}
err = dbConn.Model(&db.Conversation{
OwnerUserID: OwnerUserID,
ConversationID: conversationID,
}).Find(&conversation).Error
return conversation, err
}
func GetConversations(OwnerUserID string, conversationIDs []string) ([]db.Conversation, error) {
var conversations []db.Conversation
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return conversations, err
}
err = dbConn.Model(&db.Conversation{}).Where("conversation_id IN (?) and owner_user_id=?", conversationIDs, OwnerUserID).Find(&conversations).Error
return conversations, err
}
@@ -0,0 +1,51 @@
/*
** description("").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/3/4 11:18).
*/
package im_mysql_msg_model
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
pbMsg "Open_IM/pkg/proto/chat"
"Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/jinzhu/copier"
)
func InsertMessageToChatLog(msg pbMsg.MsgDataToMQ) error {
dbConn, err := db.DB.MysqlDB.DefaultGormDB()
if err != nil {
return err
}
chatLog := new(db.ChatLog)
copier.Copy(chatLog, msg.MsgData)
switch msg.MsgData.SessionType {
case constant.GroupChatType:
chatLog.RecvID = msg.MsgData.GroupID
case constant.SingleChatType:
chatLog.RecvID = msg.MsgData.RecvID
}
if msg.MsgData.ContentType >= constant.NotificationBegin && msg.MsgData.ContentType <= constant.NotificationEnd {
var tips server_api_params.TipsComm
_ = proto.Unmarshal(msg.MsgData.Content, &tips)
marshaler := jsonpb.Marshaler{
OrigName: true,
EnumsAsInts: false,
EmitDefaults: false,
}
chatLog.Content, _ = marshaler.MarshalToString(&tips)
} else {
chatLog.Content = string(msg.MsgData.Content)
}
chatLog.CreateTime = utils.UnixMillSecondToTime(msg.MsgData.CreateTime)
chatLog.SendTime = utils.UnixMillSecondToTime(msg.MsgData.SendTime)
log.NewDebug("test", "this is ", chatLog)
return dbConn.Table("chat_logs").Create(chatLog).Error
}
@@ -0,0 +1,36 @@
package im_mysql_msg_model
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/db"
"hash/crc32"
"strconv"
)
func getHashMsgDBAddr(userID string) string {
hCode := crc32.ChecksumIEEE([]byte(userID))
return config.Config.Mysql.DBAddress[hCode%uint32(len(config.Config.Mysql.DBAddress))]
}
func getHashMsgTableIndex(userID string) int {
hCode := crc32.ChecksumIEEE([]byte(userID))
return int(hCode % uint32(config.Config.Mysql.DBMsgTableNum))
}
func QueryUserMsgID(userID string) ([]string, error) {
dbAddress, dbTableIndex := getHashMsgDBAddr(userID), getHashMsgTableIndex(userID)
dbTableName := "receive" + strconv.Itoa(dbTableIndex)
dbConn, _ := db.DB.MysqlDB.GormDB(dbAddress, config.Config.Mysql.DBTableName)
var msgID string
var msgIDList []string
rows, _ := dbConn.Raw("select msg_id from ? where user_id = ?", dbTableName, userID).Rows()
defer rows.Close()
for rows.Next() {
rows.Scan(&msgID)
msgIDList = append(msgIDList, msgID)
}
return msgIDList, nil
}
+157
View File
@@ -0,0 +1,157 @@
package db
import (
"Open_IM/pkg/common/constant"
log2 "Open_IM/pkg/common/log"
"github.com/garyburd/redigo/redis"
)
const (
AccountTempCode = "ACCOUNT_TEMP_CODE"
resetPwdTempCode = "RESET_PWD_TEMP_CODE"
userIncrSeq = "REDIS_USER_INCR_SEQ:" // user incr seq
appleDeviceToken = "DEVICE_TOKEN"
userMinSeq = "REDIS_USER_MIN_SEQ:"
uidPidToken = "UID_PID_TOKEN_STATUS:"
conversationReceiveMessageOpt = "CON_RECV_MSG_OPT:"
GetuiToken = "GETUI"
)
func (d *DataBases) Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
con := d.redisPool.Get()
if err := con.Err(); err != nil {
log2.Error("", "", "redis cmd = %v, err = %v", cmd, err)
return nil, err
}
defer con.Close()
params := make([]interface{}, 0)
params = append(params, key)
if len(args) > 0 {
for _, v := range args {
params = append(params, v)
}
}
return con.Do(cmd, params...)
}
func (d *DataBases) JudgeAccountEXISTS(account string) (bool, error) {
key := AccountTempCode + account
return redis.Bool(d.Exec("EXISTS", key))
}
func (d *DataBases) SetAccountCode(account string, code, ttl int) (err error) {
key := AccountTempCode + account
_, err = d.Exec("SET", key, code, "ex", ttl)
return err
}
func (d *DataBases) GetAccountCode(account string) (string, error) {
key := AccountTempCode + account
return redis.String(d.Exec("GET", key))
}
//Perform seq auto-increment operation of user messages
func (d *DataBases) IncrUserSeq(uid string) (uint64, error) {
key := userIncrSeq + uid
return redis.Uint64(d.Exec("INCR", key))
}
//Get the largest Seq
func (d *DataBases) GetUserMaxSeq(uid string) (uint64, error) {
key := userIncrSeq + uid
return redis.Uint64(d.Exec("GET", key))
}
//Set the user's minimum seq
func (d *DataBases) SetUserMinSeq(uid string, minSeq uint32) (err error) {
key := userMinSeq + uid
_, err = d.Exec("SET", key, minSeq)
return err
}
//Get the smallest Seq
func (d *DataBases) GetUserMinSeq(uid string) (uint64, error) {
key := userMinSeq + uid
return redis.Uint64(d.Exec("GET", key))
}
//Store Apple's device token to redis
func (d *DataBases) SetAppleDeviceToken(accountAddress, value string) (err error) {
key := appleDeviceToken + accountAddress
_, err = d.Exec("SET", key, value)
return err
}
//Delete Apple device token
func (d *DataBases) DelAppleDeviceToken(accountAddress string) (err error) {
key := appleDeviceToken + accountAddress
_, err = d.Exec("DEL", key)
return err
}
//Store userid and platform class to redis
func (d *DataBases) AddTokenFlag(userID string, platformID int32, token string, flag int) error {
key := uidPidToken + userID + ":" + constant.PlatformIDToName(platformID)
log2.NewDebug("", "add token key is ", key)
_, err1 := d.Exec("HSet", key, token, flag)
return err1
}
func (d *DataBases) GetTokenMapByUidPid(userID, platformID string) (map[string]int, error) {
key := uidPidToken + userID + ":" + platformID
log2.NewDebug("", "get token key is ", key)
return redis.IntMap(d.Exec("HGETALL", key))
}
func (d *DataBases) SetTokenMapByUidPid(userID string, platformID int32, m map[string]int) error {
key := uidPidToken + userID + ":" + constant.PlatformIDToName(platformID)
_, err := d.Exec("hmset", key, redis.Args{}.Add().AddFlat(m)...)
return err
}
func (d *DataBases) DeleteTokenByUidPid(userID string, platformID int32, fields []string) error {
key := uidPidToken + userID + ":" + constant.PlatformIDToName(platformID)
_, err := d.Exec("HDEL", key, redis.Args{}.Add().AddFlat(fields)...)
return err
}
func (d *DataBases) SetSingleConversationRecvMsgOpt(userID, conversationID string, opt int32) error {
key := conversationReceiveMessageOpt + userID
_, err := d.Exec("HSet", key, conversationID, opt)
return err
}
func (d *DataBases) GetSingleConversationRecvMsgOpt(userID, conversationID string) (int, error) {
key := conversationReceiveMessageOpt + userID
return redis.Int(d.Exec("HGet", key, conversationID))
}
func (d *DataBases) GetAllConversationMsgOpt(userID string) (map[string]int, error) {
key := conversationReceiveMessageOpt + userID
return redis.IntMap(d.Exec("HGETALL", key))
}
func (d *DataBases) SetMultiConversationMsgOpt(userID string, m map[string]int) error {
key := conversationReceiveMessageOpt + userID
_, err := d.Exec("hmset", key, redis.Args{}.Add().AddFlat(m)...)
return err
}
func (d *DataBases) GetMultiConversationMsgOpt(userID string, conversationIDs []string) (m map[string]int, err error) {
m = make(map[string]int)
key := conversationReceiveMessageOpt + userID
i, err := redis.Ints(d.Exec("hmget", key, redis.Args{}.Add().AddFlat(conversationIDs)...))
if err != nil {
return m, err
}
for k, v := range conversationIDs {
m[v] = i[k]
}
return m, nil
}
func (d *DataBases) SetGetuiToken(token string, expireTime int64) error {
_, err := d.Exec("SET", GetuiToken, token, "ex", expireTime)
return err
}
func (d *DataBases) GetGetuiToken() (string, error) {
result, err := redis.String(d.Exec("GET", GetuiToken))
return result, err
}
+27
View File
@@ -0,0 +1,27 @@
package db
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
)
func Test_SetTokenMapByUidPid(t *testing.T) {
m := make(map[string]int, 0)
m["test1"] = 1
m["test2"] = 2
m["2332"] = 4
_ = DB.SetTokenMapByUidPid("1234", 2, m)
}
func Test_GetTokenMapByUidPid(t *testing.T) {
m, err := DB.GetTokenMapByUidPid("1234", "Android")
assert.Nil(t, err)
fmt.Println(m)
}
func TestDataBases_GetMultiConversationMsgOpt(t *testing.T) {
m, err := DB.GetMultiConversationMsgOpt("fg", []string{"user", "age", "color"})
assert.Nil(t, err)
fmt.Println(m)
}
+66
View File
@@ -0,0 +1,66 @@
/*
** description("").
** copyright('open-im,www.open-im.io').
** author("fg,Gordon@tuoyun.net").
** time(2021/5/27 10:31).
*/
package http
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
func Get(url string) (response []byte, err error) {
client := http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
//application/json; charset=utf-8
func Post(url string, data interface{}, timeOutSecond int) (content []byte, err error) {
jsonStr, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
return nil, err
}
req.Close = true
req.Header.Add("content-type", "application/json; charset=utf-8")
client := &http.Client{Timeout: time.Duration(timeOutSecond) * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return result, nil
}
func PostReturn(url string, input, output interface{}, timeOut int) error {
b, err := Post(url, input, timeOut)
if err != nil {
return err
}
if err = json.Unmarshal(b, output); err != nil {
return err
}
return nil
}
+43
View File
@@ -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)
}
+36
View File
@@ -0,0 +1,36 @@
package kafka
import (
"github.com/Shopify/sarama"
"sync"
)
type Consumer struct {
addr []string
WG sync.WaitGroup
Topic string
PartitionList []int32
Consumer sarama.Consumer
}
func NewKafkaConsumer(addr []string, topic string) *Consumer {
p := Consumer{}
p.Topic = topic
p.addr = addr
consumer, err := sarama.NewConsumer(p.addr, nil)
if err != nil {
panic(err.Error())
return nil
}
p.Consumer = consumer
partitionList, err := consumer.Partitions(p.Topic)
if err != nil {
panic(err.Error())
return nil
}
p.PartitionList = partitionList
return &p
}
+53
View File
@@ -0,0 +1,53 @@
/*
** description("").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/5/11 9:36).
*/
package kafka
import (
"context"
"github.com/Shopify/sarama"
)
type MConsumerGroup struct {
sarama.ConsumerGroup
groupID string
topics []string
}
type MConsumerGroupConfig struct {
KafkaVersion sarama.KafkaVersion
OffsetsInitial int64
IsReturnErr bool
}
func NewMConsumerGroup(consumerConfig *MConsumerGroupConfig, topics, addr []string, groupID string) *MConsumerGroup {
config := sarama.NewConfig()
config.Version = consumerConfig.KafkaVersion
config.Consumer.Offsets.Initial = consumerConfig.OffsetsInitial
config.Consumer.Return.Errors = consumerConfig.IsReturnErr
client, err := sarama.NewClient(addr, config)
if err != nil {
panic(err.Error())
}
consumerGroup, err := sarama.NewConsumerGroupFromClient(groupID, client)
if err != nil {
panic(err.Error())
}
return &MConsumerGroup{
consumerGroup,
groupID,
topics,
}
}
func (mc *MConsumerGroup) RegisterHandleAndConsumer(handler sarama.ConsumerGroupHandler) {
ctx := context.Background()
for {
err := mc.ConsumerGroup.Consume(ctx, mc.topics, handler)
if err != nil {
panic(err.Error())
}
}
}
+49
View File
@@ -0,0 +1,49 @@
package kafka
import (
log2 "Open_IM/pkg/common/log"
"github.com/Shopify/sarama"
"github.com/golang/protobuf/proto"
)
type Producer struct {
topic string
addr []string
config *sarama.Config
producer sarama.SyncProducer
}
func NewKafkaProducer(addr []string, topic string) *Producer {
p := Producer{}
p.config = sarama.NewConfig() //Instantiate a sarama Config
p.config.Producer.Return.Successes = true //Whether to enable the successes channel to be notified after the message is sent successfully
p.config.Producer.RequiredAcks = sarama.WaitForAll //Set producer Message Reply level 0 1 all
p.config.Producer.Partitioner = sarama.NewHashPartitioner //Set the hash-key automatic hash partition. When sending a message, you must specify the key value of the message. If there is no key, the partition will be selected randomly
p.addr = addr
p.topic = topic
producer, err := sarama.NewSyncProducer(p.addr, p.config) //Initialize the client
if err != nil {
panic(err.Error())
return nil
}
p.producer = producer
return &p
}
func (p *Producer) SendMessage(m proto.Message, key ...string) (int32, int64, error) {
kMsg := &sarama.ProducerMessage{}
kMsg.Topic = p.topic
if len(key) == 1 {
kMsg.Key = sarama.StringEncoder(key[0])
}
bMsg, err := proto.Marshal(m)
if err != nil {
log2.Error("", "", "proto marshal err = %s", err.Error())
return -1, -1, err
}
kMsg.Value = sarama.ByteEncoder(bMsg)
return p.producer.SendMessage(kMsg)
}
+107
View File
@@ -0,0 +1,107 @@
/*
** description("Send logs to elasticsearch hook").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/3/26 17:05).
*/
package log
import (
"Open_IM/pkg/common/config"
"context"
"fmt"
elasticV7 "github.com/olivere/elastic/v7"
"github.com/sirupsen/logrus"
"log"
"os"
"strings"
"time"
)
//esHook CUSTOMIZED ES hook
type esHook struct {
moduleName string
client *elasticV7.Client
}
//newEsHook Initialization
func newEsHook(moduleName string) *esHook {
//https://github.com/sohlich/elogrus
//client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
//if err != nil {
// log.Panic(err)
//}
//hook, err := elogrus.NewAsyncElasticHook(client, "localhost", logrus.DebugLevel, "mylog")
//if err != nil {
// log.Panic(err)
//}
es, err := elasticV7.NewClient(
elasticV7.SetURL(config.Config.Log.ElasticSearchAddr...),
elasticV7.SetBasicAuth(config.Config.Log.ElasticSearchUser, config.Config.Log.ElasticSearchPassword),
elasticV7.SetSniff(false),
elasticV7.SetHealthcheckInterval(60*time.Second),
elasticV7.SetErrorLog(log.New(os.Stderr, "ES:", log.LstdFlags)),
)
if err != nil {
log.Fatal("failed to create Elastic V7 Client: ", err)
}
//info, code, err := es.Ping(logConfig.ElasticSearch.EsAddr[0]).Do(context.Background())
//if err != nil {
// panic(err)
//}
//fmt.Printf("Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)
//
//esversion, err := es.ElasticsearchVersion(logConfig.ElasticSearch.EsAddr[0])
//if err != nil {
// panic(err)
//}
//fmt.Printf("Elasticsearch version %s\n", esversion)
return &esHook{client: es, moduleName: moduleName}
}
//Fire log hook interface
func (hook *esHook) Fire(entry *logrus.Entry) error {
doc := newEsLog(entry)
go hook.sendEs(doc)
return nil
}
func (hook *esHook) Levels() []logrus.Level {
return logrus.AllLevels
}
//sendEs
func (hook *esHook) sendEs(doc appLogDocModel) {
defer func() {
if r := recover(); r != nil {
fmt.Println("send entry to es failed: ", r)
}
}()
_, err := hook.client.Index().Index(hook.moduleName).Type(doc.indexName()).BodyJson(doc).Do(context.Background())
if err != nil {
log.Println(err)
}
}
//appLogDocModel es model
type appLogDocModel map[string]interface{}
func newEsLog(e *logrus.Entry) appLogDocModel {
ins := make(map[string]interface{})
ins["level"] = strings.ToUpper(e.Level.String())
ins["time"] = e.Time.Format("2006-01-02 15:04:05")
for kk, vv := range e.Data {
ins[kk] = vv
}
ins["tipInfo"] = e.Message
return ins
}
// indexName es index name
func (m *appLogDocModel) indexName() string {
return time.Now().Format("2006-01-02")
}
+71
View File
@@ -0,0 +1,71 @@
/*
** description("get the name and line number of the calling file hook").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/3/16 11:26).
*/
package log
import (
"fmt"
"github.com/sirupsen/logrus"
"runtime"
"strings"
)
type fileHook struct{}
func newFileHook() *fileHook {
return &fileHook{}
}
func (f *fileHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (f *fileHook) Fire(entry *logrus.Entry) error {
entry.Data["FilePath"] = findCaller(6)
return nil
}
//func (f *fileHook) Fire(entry *logrus.Entry) error {
// var s string
// _, b, c, _ := runtime.Caller(10)
// i := strings.SplitAfter(b, "/")
// if len(i) > 3 {
// s = i[len(i)-3] + i[len(i)-2] + i[len(i)-1] + ":" + utils.IntToString(c)
// }
// entry.Data["FilePath"] = s
// return nil
//}
func findCaller(skip int) string {
file := ""
line := 0
for i := 0; i < 10; i++ {
file, line = getCaller(skip + i)
if !strings.HasPrefix(file, "log") {
break
}
}
return fmt.Sprintf("%s:%d", file, line)
}
func getCaller(skip int) (string, int) {
_, file, line, ok := runtime.Caller(skip)
if !ok {
return "", 0
}
n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}
return file, line
}
+199
View File
@@ -0,0 +1,199 @@
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"
)
var logger *Logger
type Logger struct {
*logrus.Logger
Pid int
}
func init() {
logger = loggerInit("")
}
func NewPrivateLog(moduleName string) {
logger = loggerInit(moduleName)
}
func loggerInit(moduleName string) *Logger {
var logger = logrus.New()
//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)
//logger.SetOutput(os.Stdout)
//Log Console Print Style Setting
logger.SetFormatter(&nested.Formatter{
TimestampFormat: "2006-01-02 15:04:05.000",
HideKeys: false,
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
})
//File name and line number display hook
logger.AddHook(newFileHook())
//Send logs to elasticsearch hook
if config.Config.Log.ElasticSearchSwitch {
logger.AddHook(newEsHook(moduleName))
}
//Log file segmentation hook
hook := NewLfsHook(time.Duration(config.Config.Log.RotationTime)*time.Hour, config.Config.Log.RemainRotationCount, moduleName)
logger.AddHook(hook)
return &Logger{
logger,
os.Getpid(),
}
}
func NewLfsHook(rotationTime time.Duration, maxRemainNum uint, moduleName string) logrus.Hook {
lfsHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
logrus.InfoLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
logrus.WarnLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
logrus.ErrorLevel: initRotateLogs(rotationTime, maxRemainNum, "all", moduleName),
}, &nested.Formatter{
TimestampFormat: "2006-01-02 15:04:05.000",
HideKeys: false,
FieldsOrder: []string{"PID", "FilePath", "OperationID"},
})
return lfsHook
}
func initRotateLogs(rotationTime time.Duration, maxRemainNum uint, level string, moduleName string) *rotatelogs.RotateLogs {
if moduleName != "" {
moduleName = moduleName + "."
}
writer, err := rotatelogs.New(
config.Config.Log.StorageLocation+moduleName+level+"."+"%Y-%m-%d",
rotatelogs.WithRotationTime(rotationTime),
rotatelogs.WithRotationCount(maxRemainNum),
)
if err != nil {
panic(err.Error())
} else {
return writer
}
}
func Info(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Infoln(args)
}
func Error(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Errorln(args)
}
func Debug(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Debugln(args)
}
//Deprecated
func Warning(token, OperationID, format string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"PID": logger.Pid,
"OperationID": OperationID,
}).Warningf(format, args...)
}
//Deprecated
func InfoByArgs(format string, args ...interface{}) {
logger.WithFields(logrus.Fields{}).Infof(format, args)
}
//Deprecated
func ErrorByArgs(format string, args ...interface{}) {
logger.WithFields(logrus.Fields{}).Errorf(format, args...)
}
//Print log information in k, v format,
//kv is best to appear in pairs. tipInfo is the log prompt information for printing,
//and kv is the key and value for printing.
//Deprecated
func InfoByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Info(tipInfo)
}
//Deprecated
func ErrorByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Error(tipInfo)
}
//Deprecated
func DebugByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Debug(tipInfo)
}
//Deprecated
func WarnByKv(tipInfo, OperationID string, args ...interface{}) {
fields := make(logrus.Fields)
argsHandle(OperationID, fields, args)
logger.WithFields(fields).Warn(tipInfo)
}
//internal method
func argsHandle(OperationID string, fields logrus.Fields, args []interface{}) {
for i := 0; i < len(args); i += 2 {
if i+1 < len(args) {
fields[fmt.Sprintf("%v", args[i])] = args[i+1]
} else {
fields[fmt.Sprintf("%v", args[i])] = ""
}
}
fields["OperationID"] = OperationID
fields["PID"] = logger.Pid
}
func NewInfo(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Infoln(args)
}
func NewError(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Errorln(args)
}
func NewDebug(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Debugln(args)
}
func NewWarn(OperationID string, args ...interface{}) {
logger.WithFields(logrus.Fields{
"OperationID": OperationID,
"PID": logger.Pid,
}).Warnln(args)
}
+57
View File
@@ -0,0 +1,57 @@
/*
** description("").
** copyright('tuoyun,www.tuoyun.net').
** author("fg,Gordon@tuoyun.net").
** time(2021/2/22 11:52).
*/
package log
import (
"strconv"
"time"
)
const (
TimeOffset = 8 * 3600 //8 hour offset
HalfOffset = 12 * 3600 //Half-day hourly offset
)
//Get the current timestamp
func GetCurrentTimestamp() int64 {
return time.Now().Unix()
}
//Get the current 0 o'clock timestamp
func GetCurDayZeroTimestamp() int64 {
timeStr := time.Now().Format("2006-01-02")
t, _ := time.Parse("2006-01-02", timeStr)
return t.Unix() - TimeOffset
}
//Get the timestamp at 12 o'clock on the day
func GetCurDayHalfTimestamp() int64 {
return GetCurDayZeroTimestamp() + HalfOffset
}
//Get the formatted time at 0 o'clock of the day, the format is "2006-01-02_00-00-00"
func GetCurDayZeroTimeFormat() string {
return time.Unix(GetCurDayZeroTimestamp(), 0).Format("2006-01-02_15-04-05")
}
//Get the formatted time at 12 o'clock of the day, the format is "2006-01-02_12-00-00"
func GetCurDayHalfTimeFormat() string {
return time.Unix(GetCurDayZeroTimestamp()+HalfOffset, 0).Format("2006-01-02_15-04-05")
}
func GetTimeStampByFormat(datetime string) string {
timeLayout := "2006-01-02 15:04:05" //转化所需模板
loc, _ := time.LoadLocation("Local") //获取时区
tmp, _ := time.ParseInLocation(timeLayout, datetime, loc)
timestamp := tmp.Unix() //转化为时间戳 类型是int64
return strconv.FormatInt(timestamp, 10)
}
func TimeStringFormatTimeUnix(timeFormat string, timeSrc string) int64 {
tm, _ := time.Parse(timeFormat, timeSrc)
return tm.Unix()
}
@@ -0,0 +1,73 @@
package multi_terminal_login
//
//import (
// "Open_IM/internal/push/content_struct"
// "Open_IM/internal/push/logic"
// "Open_IM/pkg/common/config"
// "Open_IM/pkg/common/constant"
// "Open_IM/pkg/common/db"
// pbChat "Open_IM/pkg/proto/chat"
// "Open_IM/pkg/utils"
//)
//
//const DayOfSecond = 24*60*60
//func MultiTerminalLoginChecker(uid, token string, platformID int32) error {
// // 1.check userid and platform class 0 not exists and 1 exists
// exists, err := db.DB.ExistsUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)))
// if err != nil {
// return err
// }
// //get config multi login policy
// if config.Config.MultiLoginPolicy {
// //OnlyOneTerminalAccess policy need to check all terminal
// if constant.PlatformNameToClass(constant.PlatformIDToName(platformID)) == "PC" {
// exists, err = db.DB.ExistsUserIDAndPlatform(uid, "Mobile")
// if err != nil {
// return err
// }
// } else {
// exists, err = db.DB.ExistsUserIDAndPlatform(uid, "PC")
// if err != nil {
// return err
// }
// }
// if exists == 1 {
// err := db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
// }
// } else if config.Config.MultiLoginPolicy.MobileAndPCTerminalAccessButOtherTerminalKickEachOther {
// // common terminal need to kick eich other
// if exists == 1 {
// err := db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
// }
// }
// err = db.DB.SetUserIDAndPlatform(uid, constant.PlatformNameToClass(constant.PlatformIDToName(platformID)), token, config.Config.TokenPolicy.AccessExpire*DayOfSecond)
// if err != nil {
// return err
// }
// PushMessageToTheTerminal(uid, platformID)
// return nil
//}
////
////func PushMessageToTheTerminal(uid string, platform int32) {
////
//// logic.SendMsgByWS(&pbChat.WSToMsgSvrChatMsg{
//// SendID: uid,
//// RecvID: uid,
//// Content: content_struct.NewContentStructString(1, "", "Your account is already logged on other terminal,please confirm"),
//// SendTime: utils.GetCurrentTimestampBySecond(),
//// MsgFrom: constant.SysMsgType,
//// ContentType: constant.KickOnlineTip,
//// PlatformID: platform,
//// })
////}
+231
View File
@@ -0,0 +1,231 @@
package token_verify
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
commonDB "Open_IM/pkg/common/db"
"Open_IM/pkg/common/log"
"Open_IM/pkg/utils"
"github.com/garyburd/redigo/redis"
"github.com/golang-jwt/jwt/v4"
"time"
)
//var (
// TokenExpired = errors.New("token is timed out, please log in again")
// TokenInvalid = errors.New("token has been invalidated")
// TokenNotValidYet = errors.New("token not active yet")
// TokenMalformed = errors.New("that's not even a token")
// TokenUnknown = errors.New("couldn't handle this token")
//)
type Claims struct {
UID string
Platform string //login platform
jwt.RegisteredClaims
}
func BuildClaims(uid, platform string, ttl int64) Claims {
now := time.Now()
return Claims{
UID: uid,
Platform: platform,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(time.Duration(ttl*24) * time.Hour)), //Expiration time
IssuedAt: jwt.NewNumericDate(now), //Issuing time
NotBefore: jwt.NewNumericDate(now), //Begin Effective time
}}
}
func CreateToken(userID string, platformID int32) (string, int64, error) {
claims := BuildClaims(userID, constant.PlatformIDToName(platformID), config.Config.TokenPolicy.AccessExpire)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.Config.TokenPolicy.AccessSecret))
if err != nil {
return "", 0, err
}
//remove Invalid token
m, err := commonDB.DB.GetTokenMapByUidPid(userID, constant.PlatformIDToName(platformID))
if err != nil && err != redis.ErrNil {
return "", 0, err
}
var deleteTokenKey []string
for k, v := range m {
_, err = GetClaimFromToken(k)
if err != nil || v != constant.NormalToken {
deleteTokenKey = append(deleteTokenKey, k)
}
}
if len(deleteTokenKey) != 0 {
err = commonDB.DB.DeleteTokenByUidPid(userID, platformID, deleteTokenKey)
if err != nil {
return "", 0, err
}
}
err = commonDB.DB.AddTokenFlag(userID, platformID, tokenString, constant.NormalToken)
if err != nil {
return "", 0, err
}
return tokenString, claims.ExpiresAt.Time.Unix(), err
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.TokenPolicy.AccessSecret), nil
}
}
func GetClaimFromToken(tokensString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokensString, &Claims{}, secret())
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
return nil, &constant.ErrTokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
return nil, &constant.ErrTokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
return nil, &constant.ErrTokenNotValidYet
} else {
return nil, &constant.ErrTokenUnknown
}
} else {
return nil, &constant.ErrTokenNotValidYet
}
} else {
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
//log.NewDebug("", claims.UID, claims.Platform)
return claims, nil
}
return nil, &constant.ErrTokenNotValidYet
}
}
func IsAppManagerAccess(token string, OpUserID string) bool {
claims, err := ParseToken(token, "")
if err != nil {
return false
}
if utils.IsContain(claims.UID, config.Config.Manager.AppManagerUid) && claims.UID == OpUserID {
return true
}
return false
}
func IsManagerUserID(OpUserID string) bool {
if utils.IsContain(OpUserID, config.Config.Manager.AppManagerUid) {
return true
} else {
return false
}
}
func CheckAccess(OpUserID string, OwnerUserID string) bool {
if utils.IsContain(OpUserID, config.Config.Manager.AppManagerUid) {
return true
}
if OpUserID == OwnerUserID {
return true
}
return false
}
func GetUserIDFromToken(token string, operationID string) (bool, string) {
claims, err := ParseToken(token, operationID)
if err != nil {
log.Error(operationID, "ParseToken failed, ", err.Error(), token)
return false, ""
}
return true, claims.UID
}
func ParseTokenGetUserID(token string, operationID string) (error, string) {
claims, err := ParseToken(token, operationID)
if err != nil {
return utils.Wrap(err, ""), ""
}
return nil, claims.UID
}
func ParseToken(tokensString, operationID string) (claims *Claims, err error) {
claims, err = GetClaimFromToken(tokensString)
if err != nil {
log.NewError(operationID, "token validate err", err.Error(), tokensString)
return nil, utils.Wrap(err, "")
}
m, err := commonDB.DB.GetTokenMapByUidPid(claims.UID, claims.Platform)
if err != nil {
log.NewError(operationID, "get token from redis err", err.Error(), tokensString)
return nil, utils.Wrap(&constant.ErrTokenInvalid, "get token from redis err")
}
if m == nil {
log.NewError(operationID, "get token from redis err", "m is nil", tokensString)
return nil, utils.Wrap(&constant.ErrTokenInvalid, "get token from redis err")
}
if v, ok := m[tokensString]; ok {
switch v {
case constant.NormalToken:
log.NewDebug(operationID, "this is normal return", claims)
return claims, nil
case constant.InValidToken:
return nil, utils.Wrap(&constant.ErrTokenInvalid, "")
case constant.KickedToken:
log.Error(operationID, "this token has been kicked by other same terminal ", constant.ErrTokenKicked)
return nil, utils.Wrap(&constant.ErrTokenKicked, "this token has been kicked by other same terminal ")
case constant.ExpiredToken:
return nil, utils.Wrap(&constant.ErrTokenExpired, "")
default:
return nil, utils.Wrap(&constant.ErrTokenUnknown, "")
}
}
log.NewError(operationID, "redis token map not find", constant.ErrTokenUnknown)
return nil, utils.Wrap(&constant.ErrTokenUnknown, "redis token map not find")
}
//func MakeTheTokenInvalid(currentClaims *Claims, platformClass string) (bool, error) {
// storedRedisTokenInterface, err := db.DB.GetPlatformToken(currentClaims.UID, platformClass)
// if err != nil {
// return false, err
// }
// storedRedisPlatformClaims, err := ParseRedisInterfaceToken(storedRedisTokenInterface)
// if err != nil {
// return false, err
// }
// //if issue time less than redis token then make this token invalid
// if currentClaims.IssuedAt.Time.Unix() < storedRedisPlatformClaims.IssuedAt.Time.Unix() {
// return true, constant.TokenInvalid
// }
// return false, nil
//}
func ParseRedisInterfaceToken(redisToken interface{}) (*Claims, error) {
return GetClaimFromToken(string(redisToken.([]uint8)))
}
//Validation token, false means failure, true means successful verification
func VerifyToken(token, uid string) (bool, error) {
claims, err := ParseToken(token, "")
if err != nil {
return false, err
}
if claims.UID != uid {
return false, &constant.ErrTokenUnknown
}
log.NewDebug("", claims.UID, claims.Platform)
return true, nil
}
func WsVerifyToken(token, uid string, platformID string) (bool, error, string) {
claims, err := ParseToken(token, "")
if err != nil {
return false, err, "parse token err"
}
if claims.UID != uid {
return false, &constant.ErrTokenUnknown, "uid is not same to token uid"
}
if claims.Platform != constant.PlatformIDToName(utils.StringToInt32(platformID)) {
return false, &constant.ErrTokenUnknown, "platform is not same to token platform"
}
log.NewDebug("", claims.UID, claims.Platform)
return true, nil, ""
}
+161
View File
@@ -0,0 +1,161 @@
package utils
import (
db "Open_IM/pkg/common/db"
imdb "Open_IM/pkg/common/db/mysql_model/im_mysql_model"
"Open_IM/pkg/common/token_verify"
open_im_sdk "Open_IM/pkg/proto/sdk_ws"
"Open_IM/pkg/utils"
"math/rand"
"strconv"
"time"
)
func OperationIDGenerator() string {
return strconv.FormatInt(time.Now().UnixNano()+int64(rand.Uint32()), 10)
}
func FriendOpenIMCopyDB(dst *db.Friend, src *open_im_sdk.FriendInfo) {
utils.CopyStructFields(dst, src)
dst.FriendUserID = src.FriendUser.UserID
dst.CreateTime = utils.UnixSecondToTime(int64(src.CreateTime))
}
func FriendDBCopyOpenIM(dst *open_im_sdk.FriendInfo, src *db.Friend) error {
utils.CopyStructFields(dst, src)
user, err := imdb.GetUserByUserID(src.FriendUserID)
if err != nil {
return utils.Wrap(err, "")
}
utils.CopyStructFields(dst.FriendUser, user)
dst.CreateTime = uint32(src.CreateTime.Unix())
if dst.FriendUser == nil {
dst.FriendUser = &open_im_sdk.UserInfo{}
}
dst.FriendUser.CreateTime = uint32(user.CreateTime.Unix())
return nil
}
//
func FriendRequestOpenIMCopyDB(dst *db.FriendRequest, src *open_im_sdk.FriendRequest) {
utils.CopyStructFields(dst, src)
dst.CreateTime = utils.UnixSecondToTime(int64(src.CreateTime))
dst.HandleTime = utils.UnixSecondToTime(int64(src.HandleTime))
}
func FriendRequestDBCopyOpenIM(dst *open_im_sdk.FriendRequest, src *db.FriendRequest) error {
utils.CopyStructFields(dst, src)
user, err := imdb.GetUserByUserID(src.FromUserID)
if err != nil {
return utils.Wrap(err, "")
}
dst.FromNickname = user.Nickname
dst.FromFaceURL = user.FaceURL
dst.FromGender = user.Gender
user, err = imdb.GetUserByUserID(src.ToUserID)
if err != nil {
return utils.Wrap(err, "")
}
dst.ToNickname = user.Nickname
dst.ToFaceURL = user.FaceURL
dst.ToGender = user.Gender
dst.CreateTime = uint32(src.CreateTime.Unix())
dst.HandleTime = uint32(src.HandleTime.Unix())
return nil
}
func BlackOpenIMCopyDB(dst *db.Black, src *open_im_sdk.BlackInfo) {
utils.CopyStructFields(dst, src)
dst.BlockUserID = src.BlackUserInfo.UserID
dst.CreateTime = utils.UnixSecondToTime(int64(src.CreateTime))
}
func BlackDBCopyOpenIM(dst *open_im_sdk.BlackInfo, src *db.Black) error {
utils.CopyStructFields(dst, src)
dst.CreateTime = uint32(src.CreateTime.Unix())
user, err := imdb.GetUserByUserID(src.BlockUserID)
if err != nil {
return utils.Wrap(err, "")
}
utils.CopyStructFields(dst.BlackUserInfo, user)
return nil
}
func GroupOpenIMCopyDB(dst *db.Group, src *open_im_sdk.GroupInfo) {
utils.CopyStructFields(dst, src)
}
func GroupDBCopyOpenIM(dst *open_im_sdk.GroupInfo, src *db.Group) error {
utils.CopyStructFields(dst, src)
user, err := imdb.GetGroupOwnerInfoByGroupID(src.GroupID)
if err != nil {
return utils.Wrap(err, "")
}
dst.OwnerUserID = user.UserID
dst.MemberCount, err = imdb.GetGroupMemberNumByGroupID(src.GroupID)
if err != nil {
return utils.Wrap(err, "")
}
dst.CreateTime = uint32(src.CreateTime.Unix())
return nil
}
func GroupMemberOpenIMCopyDB(dst *db.GroupMember, src *open_im_sdk.GroupMemberFullInfo) {
utils.CopyStructFields(dst, src)
}
func GroupMemberDBCopyOpenIM(dst *open_im_sdk.GroupMemberFullInfo, src *db.GroupMember) error {
utils.CopyStructFields(dst, src)
if token_verify.IsManagerUserID(src.UserID) {
u, err := imdb.GetUserByUserID(src.UserID)
if err != nil {
return utils.Wrap(err, "")
}
utils.CopyStructFields(dst, u)
dst.AppMangerLevel = 1
}
dst.JoinTime = int32(src.JoinTime.Unix())
if src.MuteEndTime.Unix() < 0 {
dst.JoinTime = 0
return nil
}
dst.MuteEndTime = uint32(src.MuteEndTime.Unix())
if dst.MuteEndTime < uint32(time.Now().Unix()) {
dst.MuteEndTime = 0
}
return nil
}
func GroupRequestOpenIMCopyDB(dst *db.GroupRequest, src *open_im_sdk.GroupRequest) {
utils.CopyStructFields(dst, src)
}
func GroupRequestDBCopyOpenIM(dst *open_im_sdk.GroupRequest, src *db.GroupRequest) {
utils.CopyStructFields(dst, src)
dst.ReqTime = uint32(src.ReqTime.Unix())
dst.HandleTime = uint32(src.HandledTime.Unix())
}
func UserOpenIMCopyDB(dst *db.User, src *open_im_sdk.UserInfo) {
utils.CopyStructFields(dst, src)
dst.Birth = utils.UnixSecondToTime(int64(src.Birth))
dst.CreateTime = utils.UnixSecondToTime(int64(src.CreateTime))
}
func UserDBCopyOpenIM(dst *open_im_sdk.UserInfo, src *db.User) {
utils.CopyStructFields(dst, src)
dst.CreateTime = uint32(src.CreateTime.Unix())
dst.Birth = uint32(src.Birth.Unix())
}
func UserDBCopyOpenIMPublicUser(dst *open_im_sdk.PublicUserInfo, src *db.User) {
utils.CopyStructFields(dst, src)
}
//
//func PublicUserDBCopyOpenIM(dst *open_im_sdk.PublicUserInfo, src *db.User){
//
//}
+254
View File
@@ -0,0 +1,254 @@
// Package grpcpool provides a pool of grpc clients
package getcdv3
import (
"context"
"errors"
"sync"
"time"
"google.golang.org/grpc"
)
var (
// ErrClosed is the error when the client pool is closed
ErrClosed = errors.New("grpc pool: client pool is closed")
// ErrTimeout is the error when the client pool timed out
ErrTimeout = errors.New("grpc pool: client pool timed out")
// ErrAlreadyClosed is the error when the client conn was already closed
ErrAlreadyClosed = errors.New("grpc pool: the connection was already closed")
// ErrFullPool is the error when the pool is already full
ErrFullPool = errors.New("grpc pool: closing a ClientConn into a full pool")
)
// Factory is a function type creating a grpc client
type Factory func(schema, etcdaddr, servicename string) (*grpc.ClientConn, error)
// FactoryWithContext is a function type creating a grpc client
// that accepts the context parameter that could be passed from
// Get or NewWithContext method.
type FactoryWithContext func(context.Context) (*grpc.ClientConn, error)
// Pool is the grpc client pool
type Pool struct {
clients chan ClientConn
factory FactoryWithContext
idleTimeout time.Duration
maxLifeDuration time.Duration
mu sync.RWMutex
}
// ClientConn is the wrapper for a grpc client conn
type ClientConn struct {
*grpc.ClientConn
pool *Pool
timeUsed time.Time
timeInitiated time.Time
unhealthy bool
}
// New creates a new clients pool with the given initial and maximum capacity,
// and the timeout for the idle clients. Returns an error if the initial
// clients could not be created
func New(factory Factory, schema, etcdaddr, servicename string, init, capacity int, idleTimeout time.Duration,
maxLifeDuration ...time.Duration) (*Pool, error) {
return NewWithContext(context.Background(), func(ctx context.Context) (*grpc.ClientConn, error) { return factory(schema, etcdaddr, servicename) },
init, capacity, idleTimeout, maxLifeDuration...)
}
// NewWithContext creates a new clients pool with the given initial and maximum
// capacity, and the timeout for the idle clients. The context parameter would
// be passed to the factory method during initialization. Returns an error if the
// initial clients could not be created.
func NewWithContext(ctx context.Context, factory FactoryWithContext, init, capacity int, idleTimeout time.Duration,
maxLifeDuration ...time.Duration) (*Pool, error) {
if capacity <= 0 {
capacity = 1
}
if init < 0 {
init = 0
}
if init > capacity {
init = capacity
}
p := &Pool{
clients: make(chan ClientConn, capacity),
factory: factory,
idleTimeout: idleTimeout,
}
if len(maxLifeDuration) > 0 {
p.maxLifeDuration = maxLifeDuration[0]
}
for i := 0; i < init; i++ {
c, err := factory(ctx)
if err != nil {
return nil, err
}
p.clients <- ClientConn{
ClientConn: c,
pool: p,
timeUsed: time.Now(),
timeInitiated: time.Now(),
}
}
// Fill the rest of the pool with empty clients
for i := 0; i < capacity-init; i++ {
p.clients <- ClientConn{
pool: p,
}
}
return p, nil
}
func (p *Pool) getClients() chan ClientConn {
p.mu.RLock()
defer p.mu.RUnlock()
return p.clients
}
// Close empties the pool calling Close on all its clients.
// You can call Close while there are outstanding clients.
// The pool channel is then closed, and Get will not be allowed anymore
func (p *Pool) Close() {
p.mu.Lock()
clients := p.clients
p.clients = nil
p.mu.Unlock()
if clients == nil {
return
}
close(clients)
for client := range clients {
if client.ClientConn == nil {
continue
}
client.ClientConn.Close()
}
}
// IsClosed returns true if the client pool is closed.
func (p *Pool) IsClosed() bool {
return p == nil || p.getClients() == nil
}
// Get will return the next available client. If capacity
// has not been reached, it will create a new one using the factory. Otherwise,
// it will wait till the next client becomes available or a timeout.
// A timeout of 0 is an indefinite wait
func (p *Pool) Get(ctx context.Context) (*ClientConn, error) {
clients := p.getClients()
if clients == nil {
return nil, ErrClosed
}
wrapper := ClientConn{
pool: p,
}
select {
case wrapper = <-clients:
// All good
case <-ctx.Done():
return nil, ErrTimeout // it would better returns ctx.Err()
}
// If the wrapper was idle too long, close the connection and create a new
// one. It's safe to assume that there isn't any newer client as the client
// we fetched is the first in the channel
idleTimeout := p.idleTimeout
if wrapper.ClientConn != nil && idleTimeout > 0 &&
wrapper.timeUsed.Add(idleTimeout).Before(time.Now()) {
wrapper.ClientConn.Close()
wrapper.ClientConn = nil
}
var err error
if wrapper.ClientConn == nil {
wrapper.ClientConn, err = p.factory(ctx)
if err != nil {
// If there was an error, we want to put back a placeholder
// client in the channel
clients <- ClientConn{
pool: p,
}
}
// This is a new connection, reset its initiated time
wrapper.timeInitiated = time.Now()
}
return &wrapper, err
}
// Unhealthy marks the client conn as unhealthy, so that the connection
// gets reset when closed
func (c *ClientConn) Unhealthy() {
c.unhealthy = true
}
// Close returns a ClientConn to the pool. It is safe to call multiple time,
// but will return an error after first time
func (c *ClientConn) Close() error {
if c == nil {
return nil
}
if c.ClientConn == nil {
return ErrAlreadyClosed
}
if c.pool.IsClosed() {
return ErrClosed
}
// If the wrapper connection has become too old, we want to recycle it. To
// clarify the logic: if the sum of the initialization time and the max
// duration is before Now(), it means the initialization is so old adding
// the maximum duration couldn't put in the future. This sum therefore
// corresponds to the cut-off point: if it's in the future we still have
// time, if it's in the past it's too old
maxDuration := c.pool.maxLifeDuration
if maxDuration > 0 && c.timeInitiated.Add(maxDuration).Before(time.Now()) {
c.Unhealthy()
}
// We're cloning the wrapper so we can set ClientConn to nil in the one
// used by the user
wrapper := ClientConn{
pool: c.pool,
ClientConn: c.ClientConn,
timeUsed: time.Now(),
}
if c.unhealthy {
wrapper.ClientConn.Close()
wrapper.ClientConn = nil
} else {
wrapper.timeInitiated = c.timeInitiated
}
select {
case c.pool.clients <- wrapper:
// All good
default:
return ErrFullPool
}
c.ClientConn = nil // Mark as closed
return nil
}
// Capacity returns the capacity
func (p *Pool) Capacity() int {
if p.IsClosed() {
return 0
}
return cap(p.clients)
}
// Available returns the number of currently unused clients
func (p *Pool) Available() int {
if p.IsClosed() {
return 0
}
return len(p.clients)
}
+118
View File
@@ -0,0 +1,118 @@
package getcdv3
import (
"Open_IM/pkg/common/log"
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"net"
"strconv"
"strings"
"time"
)
type RegEtcd struct {
cli *clientv3.Client
ctx context.Context
cancel context.CancelFunc
key string
}
var rEtcd *RegEtcd
// "%s:///%s/"
func GetPrefix(schema, serviceName string) string {
return fmt.Sprintf("%s:///%s/", schema, serviceName)
}
// "%s:///%s"
func GetPrefix4Unique(schema, serviceName string) string {
return fmt.Sprintf("%s:///%s", schema, serviceName)
}
// "%s:///%s/" -> "%s:///%s:ip:port"
func RegisterEtcd4Unique(schema, etcdAddr, myHost string, myPort int, serviceName string, ttl int) error {
serviceName = serviceName + ":" + net.JoinHostPort(myHost, strconv.Itoa(myPort))
return RegisterEtcd(schema, etcdAddr, myHost, myPort, serviceName, ttl)
}
//etcdAddr separated by commas
func RegisterEtcd(schema, etcdAddr, myHost string, myPort int, serviceName string, ttl int) error {
ttl = ttl * 3
cli, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(etcdAddr, ","), DialTimeout: 5 * time.Second})
log.Info("", "RegisterEtcd, ", schema, etcdAddr, myHost, myPort, serviceName, ttl)
if err != nil {
return fmt.Errorf("create etcd clientv3 client failed, errmsg:%v, etcd addr:%s", err, etcdAddr)
}
//lease
ctx, cancel := context.WithCancel(context.Background())
resp, err := cli.Grant(ctx, int64(ttl))
if err != nil {
return fmt.Errorf("grant failed")
}
// schema:///serviceName/ip:port ->ip:port
serviceValue := net.JoinHostPort(myHost, strconv.Itoa(myPort))
serviceKey := GetPrefix(schema, serviceName) + serviceValue
//set key->value
if _, err := cli.Put(ctx, serviceKey, serviceValue, clientv3.WithLease(resp.ID)); err != nil {
return fmt.Errorf("put failed, errmsg:%v key:%s, value:%s", err, serviceKey, serviceValue)
}
//keepalive
kresp, err := cli.KeepAlive(ctx, resp.ID)
if err != nil {
return fmt.Errorf("keepalive failed, errmsg:%v, lease id:%d", err, resp.ID)
}
//log.Info("", "RegisterEtcd ok ")
go func() {
for {
select {
case pv, ok := <-kresp:
if ok == true {
log.Debug("", "KeepAlive kresp ok", pv)
} else {
log.Error("", "KeepAlive kresp failed", pv)
t := time.NewTicker(time.Duration(ttl/2) * time.Second)
for {
select {
case <-t.C:
}
ctx, _ := context.WithCancel(context.Background())
resp, err := cli.Grant(ctx, int64(ttl))
if err != nil {
log.Error("", "Grant failed ", err.Error())
continue
}
if _, err := cli.Put(ctx, serviceKey, serviceValue, clientv3.WithLease(resp.ID)); err != nil {
log.Error("", "etcd Put failed ", err.Error(), serviceKey, serviceValue, resp.ID)
continue
} else {
log.Info("", "etcd Put ok", serviceKey, serviceValue, resp.ID)
}
}
}
}
}
}()
rEtcd = &RegEtcd{ctx: ctx,
cli: cli,
cancel: cancel,
key: serviceKey}
return nil
}
func UnRegisterEtcd() {
//delete
rEtcd.cancel()
rEtcd.cli.Delete(rEtcd.ctx, rEtcd.key)
}
+262
View File
@@ -0,0 +1,262 @@
package getcdv3
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/mvcc/mvccpb"
//"google.golang.org/genproto/googleapis/ads/googleads/v1/services"
"google.golang.org/grpc"
"google.golang.org/grpc/balancer/roundrobin"
"google.golang.org/grpc/resolver"
"strings"
"sync"
"time"
)
type Resolver struct {
cc resolver.ClientConn
serviceName string
grpcClientConn *grpc.ClientConn
cli *clientv3.Client
schema string
etcdAddr string
watchStartRevision int64
}
var (
nameResolver = make(map[string]*Resolver)
rwNameResolverMutex sync.RWMutex
)
func NewResolver(schema, etcdAddr, serviceName string) (*Resolver, error) {
etcdCli, err := clientv3.New(clientv3.Config{
Endpoints: strings.Split(etcdAddr, ","),
})
if err != nil {
return nil, err
}
var r Resolver
r.serviceName = serviceName
r.cli = etcdCli
r.schema = schema
r.etcdAddr = etcdAddr
resolver.Register(&r)
conn, err := grpc.Dial(
GetPrefix(schema, serviceName),
grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
grpc.WithInsecure(),
grpc.WithTimeout(time.Duration(5)*time.Second),
)
if err == nil {
r.grpcClientConn = conn
}
return &r, err
}
func (r1 *Resolver) ResolveNow(rn resolver.ResolveNowOptions) {
}
func (r1 *Resolver) Close() {
}
func GetConn(schema, etcdaddr, serviceName string) *grpc.ClientConn {
rwNameResolverMutex.RLock()
r, ok := nameResolver[schema+serviceName]
rwNameResolverMutex.RUnlock()
if ok {
return r.grpcClientConn
}
rwNameResolverMutex.Lock()
r, ok = nameResolver[schema+serviceName]
if ok {
rwNameResolverMutex.Unlock()
return r.grpcClientConn
}
r, err := NewResolver(schema, etcdaddr, serviceName)
if err != nil {
rwNameResolverMutex.Unlock()
return nil
}
nameResolver[schema+serviceName] = r
rwNameResolverMutex.Unlock()
return r.grpcClientConn
}
func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) {
if r.cli == nil {
return nil, fmt.Errorf("etcd clientv3 client failed, etcd:%s", target)
}
r.cc = cc
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// "%s:///%s"
prefix := GetPrefix(r.schema, r.serviceName)
// get key first
resp, err := r.cli.Get(ctx, prefix, clientv3.WithPrefix())
if err == nil {
var addrList []resolver.Address
for i := range resp.Kvs {
//log.Debug("", "init addr: ", string(resp.Kvs[i].Value))
addrList = append(addrList, resolver.Address{Addr: string(resp.Kvs[i].Value)})
}
r.cc.UpdateState(resolver.State{Addresses: addrList})
r.watchStartRevision = resp.Header.Revision + 1
go r.watch(prefix, addrList)
} else {
return nil, fmt.Errorf("etcd get failed, prefix: %s", prefix)
}
return r, nil
}
func (r *Resolver) Scheme() string {
return r.schema
}
func exists(addrList []resolver.Address, addr string) bool {
for _, v := range addrList {
if v.Addr == addr {
return true
}
}
return false
}
func remove(s []resolver.Address, addr string) ([]resolver.Address, bool) {
for i := range s {
if s[i].Addr == addr {
s[i] = s[len(s)-1]
return s[:len(s)-1], true
}
}
return nil, false
}
func (r *Resolver) watch(prefix string, addrList []resolver.Address) {
rch := r.cli.Watch(context.Background(), prefix, clientv3.WithPrefix(), clientv3.WithPrefix())
for n := range rch {
flag := 0
for _, ev := range n.Events {
switch ev.Type {
case mvccpb.PUT:
if !exists(addrList, string(ev.Kv.Value)) {
flag = 1
addrList = append(addrList, resolver.Address{Addr: string(ev.Kv.Value)})
//log.Debug("", "after add, new list: ", addrList)
}
case mvccpb.DELETE:
//log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value))
i := strings.LastIndexAny(string(ev.Kv.Key), "/")
if i < 0 {
return
}
t := string(ev.Kv.Key)[i+1:]
//log.Debug("remove addr key: ", string(ev.Kv.Key), "value:", string(ev.Kv.Value), "addr:", t)
if s, ok := remove(addrList, t); ok {
flag = 1
addrList = s
//log.Debug("after remove, new list: ", addrList)
}
}
}
if flag == 1 {
r.cc.UpdateState(resolver.State{Addresses: addrList})
//log.Debug("update: ", addrList)
}
}
}
func GetConn4Unique(schema, etcdaddr, servicename string) []*grpc.ClientConn {
gEtcdCli, err := clientv3.New(clientv3.Config{Endpoints: strings.Split(etcdaddr, ",")})
if err != nil {
//log.Error("clientv3.New failed", err.Error())
return nil
}
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
// "%s:///%s"
prefix := GetPrefix4Unique(schema, servicename)
resp, err := gEtcdCli.Get(ctx, prefix, clientv3.WithPrefix())
// "%s:///%s:ip:port" -> %s:ip:port
allService := make([]string, 0)
if err == nil {
for i := range resp.Kvs {
k := string(resp.Kvs[i].Key)
b := strings.LastIndex(k, "///")
k1 := k[b+len("///"):]
e := strings.Index(k1, "/")
k2 := k1[:e]
allService = append(allService, k2)
}
} else {
gEtcdCli.Close()
//log.Error("gEtcdCli.Get failed", err.Error())
return nil
}
gEtcdCli.Close()
allConn := make([]*grpc.ClientConn, 0)
for _, v := range allService {
r := GetConn(schema, etcdaddr, v)
allConn = append(allConn, r)
}
return allConn
}
var (
service2pool = make(map[string]*Pool)
service2poolMu sync.Mutex
)
func GetconnFactory(schema, etcdaddr, servicename string) (*grpc.ClientConn, error) {
c := GetConn(schema, etcdaddr, servicename)
if c != nil {
return c, nil
} else {
return c, fmt.Errorf("GetConn failed")
}
}
func GetConnPool(schema, etcdaddr, servicename string) (*ClientConn, error) {
//get pool
p := NewPool(schema, etcdaddr, servicename)
//poo->get
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(1000*time.Millisecond))
c, err := p.Get(ctx)
//log.Info("", "Get ", err)
return c, err
}
func NewPool(schema, etcdaddr, servicename string) *Pool {
if _, ok := service2pool[schema+servicename]; !ok {
//
service2poolMu.Lock()
if _, ok1 := service2pool[schema+servicename]; !ok1 {
p, err := New(GetconnFactory, schema, etcdaddr, servicename, 5, 10, 1)
if err == nil {
service2pool[schema+servicename] = p
}
}
service2poolMu.Unlock()
}
return service2pool[schema+servicename]
}
func GetGrpcConn(schema, etcdaddr, servicename string) *grpc.ClientConn {
return nameResolver[schema+servicename].grpcClientConn
}
+317
View File
@@ -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",
}
+18
View File
@@ -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);
}
+414
View File
@@ -0,0 +1,414 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: auth/auth.proto
package pbAuth // import "./auth"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import sdk_ws "Open_IM/pkg/proto/sdk_ws"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type CommonResp struct {
ErrCode int32 `protobuf:"varint,1,opt,name=errCode" json:"errCode,omitempty"`
ErrMsg string `protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *CommonResp) Reset() { *m = CommonResp{} }
func (m *CommonResp) String() string { return proto.CompactTextString(m) }
func (*CommonResp) ProtoMessage() {}
func (*CommonResp) Descriptor() ([]byte, []int) {
return fileDescriptor_auth_88965eda3ab7f34d, []int{0}
}
func (m *CommonResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_CommonResp.Unmarshal(m, b)
}
func (m *CommonResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_CommonResp.Marshal(b, m, deterministic)
}
func (dst *CommonResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_CommonResp.Merge(dst, src)
}
func (m *CommonResp) XXX_Size() int {
return xxx_messageInfo_CommonResp.Size(m)
}
func (m *CommonResp) XXX_DiscardUnknown() {
xxx_messageInfo_CommonResp.DiscardUnknown(m)
}
var xxx_messageInfo_CommonResp proto.InternalMessageInfo
func (m *CommonResp) GetErrCode() int32 {
if m != nil {
return m.ErrCode
}
return 0
}
func (m *CommonResp) GetErrMsg() string {
if m != nil {
return m.ErrMsg
}
return ""
}
type UserRegisterReq struct {
UserInfo *sdk_ws.UserInfo `protobuf:"bytes,1,opt,name=UserInfo" json:"UserInfo,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=OperationID" json:"OperationID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *UserRegisterReq) Reset() { *m = UserRegisterReq{} }
func (m *UserRegisterReq) String() string { return proto.CompactTextString(m) }
func (*UserRegisterReq) ProtoMessage() {}
func (*UserRegisterReq) Descriptor() ([]byte, []int) {
return fileDescriptor_auth_88965eda3ab7f34d, []int{1}
}
func (m *UserRegisterReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_UserRegisterReq.Unmarshal(m, b)
}
func (m *UserRegisterReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_UserRegisterReq.Marshal(b, m, deterministic)
}
func (dst *UserRegisterReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_UserRegisterReq.Merge(dst, src)
}
func (m *UserRegisterReq) XXX_Size() int {
return xxx_messageInfo_UserRegisterReq.Size(m)
}
func (m *UserRegisterReq) XXX_DiscardUnknown() {
xxx_messageInfo_UserRegisterReq.DiscardUnknown(m)
}
var xxx_messageInfo_UserRegisterReq proto.InternalMessageInfo
func (m *UserRegisterReq) GetUserInfo() *sdk_ws.UserInfo {
if m != nil {
return m.UserInfo
}
return nil
}
func (m *UserRegisterReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
type UserRegisterResp struct {
CommonResp *CommonResp `protobuf:"bytes,1,opt,name=CommonResp" json:"CommonResp,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *UserRegisterResp) Reset() { *m = UserRegisterResp{} }
func (m *UserRegisterResp) String() string { return proto.CompactTextString(m) }
func (*UserRegisterResp) ProtoMessage() {}
func (*UserRegisterResp) Descriptor() ([]byte, []int) {
return fileDescriptor_auth_88965eda3ab7f34d, []int{2}
}
func (m *UserRegisterResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_UserRegisterResp.Unmarshal(m, b)
}
func (m *UserRegisterResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_UserRegisterResp.Marshal(b, m, deterministic)
}
func (dst *UserRegisterResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_UserRegisterResp.Merge(dst, src)
}
func (m *UserRegisterResp) XXX_Size() int {
return xxx_messageInfo_UserRegisterResp.Size(m)
}
func (m *UserRegisterResp) XXX_DiscardUnknown() {
xxx_messageInfo_UserRegisterResp.DiscardUnknown(m)
}
var xxx_messageInfo_UserRegisterResp proto.InternalMessageInfo
func (m *UserRegisterResp) GetCommonResp() *CommonResp {
if m != nil {
return m.CommonResp
}
return nil
}
type UserTokenReq struct {
Platform int32 `protobuf:"varint,1,opt,name=Platform" json:"Platform,omitempty"`
FromUserID string `protobuf:"bytes,2,opt,name=FromUserID" json:"FromUserID,omitempty"`
OpUserID string `protobuf:"bytes,3,opt,name=OpUserID" json:"OpUserID,omitempty"`
OperationID string `protobuf:"bytes,4,opt,name=OperationID" json:"OperationID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *UserTokenReq) Reset() { *m = UserTokenReq{} }
func (m *UserTokenReq) String() string { return proto.CompactTextString(m) }
func (*UserTokenReq) ProtoMessage() {}
func (*UserTokenReq) Descriptor() ([]byte, []int) {
return fileDescriptor_auth_88965eda3ab7f34d, []int{3}
}
func (m *UserTokenReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_UserTokenReq.Unmarshal(m, b)
}
func (m *UserTokenReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_UserTokenReq.Marshal(b, m, deterministic)
}
func (dst *UserTokenReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_UserTokenReq.Merge(dst, src)
}
func (m *UserTokenReq) XXX_Size() int {
return xxx_messageInfo_UserTokenReq.Size(m)
}
func (m *UserTokenReq) XXX_DiscardUnknown() {
xxx_messageInfo_UserTokenReq.DiscardUnknown(m)
}
var xxx_messageInfo_UserTokenReq proto.InternalMessageInfo
func (m *UserTokenReq) GetPlatform() int32 {
if m != nil {
return m.Platform
}
return 0
}
func (m *UserTokenReq) GetFromUserID() string {
if m != nil {
return m.FromUserID
}
return ""
}
func (m *UserTokenReq) GetOpUserID() string {
if m != nil {
return m.OpUserID
}
return ""
}
func (m *UserTokenReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
type UserTokenResp struct {
CommonResp *CommonResp `protobuf:"bytes,1,opt,name=CommonResp" json:"CommonResp,omitempty"`
Token string `protobuf:"bytes,2,opt,name=Token" json:"Token,omitempty"`
ExpiredTime int64 `protobuf:"varint,3,opt,name=ExpiredTime" json:"ExpiredTime,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *UserTokenResp) Reset() { *m = UserTokenResp{} }
func (m *UserTokenResp) String() string { return proto.CompactTextString(m) }
func (*UserTokenResp) ProtoMessage() {}
func (*UserTokenResp) Descriptor() ([]byte, []int) {
return fileDescriptor_auth_88965eda3ab7f34d, []int{4}
}
func (m *UserTokenResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_UserTokenResp.Unmarshal(m, b)
}
func (m *UserTokenResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_UserTokenResp.Marshal(b, m, deterministic)
}
func (dst *UserTokenResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_UserTokenResp.Merge(dst, src)
}
func (m *UserTokenResp) XXX_Size() int {
return xxx_messageInfo_UserTokenResp.Size(m)
}
func (m *UserTokenResp) XXX_DiscardUnknown() {
xxx_messageInfo_UserTokenResp.DiscardUnknown(m)
}
var xxx_messageInfo_UserTokenResp proto.InternalMessageInfo
func (m *UserTokenResp) GetCommonResp() *CommonResp {
if m != nil {
return m.CommonResp
}
return nil
}
func (m *UserTokenResp) GetToken() string {
if m != nil {
return m.Token
}
return ""
}
func (m *UserTokenResp) GetExpiredTime() int64 {
if m != nil {
return m.ExpiredTime
}
return 0
}
func init() {
proto.RegisterType((*CommonResp)(nil), "pbAuth.CommonResp")
proto.RegisterType((*UserRegisterReq)(nil), "pbAuth.UserRegisterReq")
proto.RegisterType((*UserRegisterResp)(nil), "pbAuth.UserRegisterResp")
proto.RegisterType((*UserTokenReq)(nil), "pbAuth.UserTokenReq")
proto.RegisterType((*UserTokenResp)(nil), "pbAuth.UserTokenResp")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// Client API for Auth service
type AuthClient interface {
UserRegister(ctx context.Context, in *UserRegisterReq, opts ...grpc.CallOption) (*UserRegisterResp, error)
UserToken(ctx context.Context, in *UserTokenReq, opts ...grpc.CallOption) (*UserTokenResp, error)
}
type authClient struct {
cc *grpc.ClientConn
}
func NewAuthClient(cc *grpc.ClientConn) AuthClient {
return &authClient{cc}
}
func (c *authClient) UserRegister(ctx context.Context, in *UserRegisterReq, opts ...grpc.CallOption) (*UserRegisterResp, error) {
out := new(UserRegisterResp)
err := grpc.Invoke(ctx, "/pbAuth.Auth/UserRegister", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authClient) UserToken(ctx context.Context, in *UserTokenReq, opts ...grpc.CallOption) (*UserTokenResp, error) {
out := new(UserTokenResp)
err := grpc.Invoke(ctx, "/pbAuth.Auth/UserToken", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Auth service
type AuthServer interface {
UserRegister(context.Context, *UserRegisterReq) (*UserRegisterResp, error)
UserToken(context.Context, *UserTokenReq) (*UserTokenResp, error)
}
func RegisterAuthServer(s *grpc.Server, srv AuthServer) {
s.RegisterService(&_Auth_serviceDesc, srv)
}
func _Auth_UserRegister_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserRegisterReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServer).UserRegister(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbAuth.Auth/UserRegister",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServer).UserRegister(ctx, req.(*UserRegisterReq))
}
return interceptor(ctx, in, info, handler)
}
func _Auth_UserToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UserTokenReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServer).UserToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbAuth.Auth/UserToken",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServer).UserToken(ctx, req.(*UserTokenReq))
}
return interceptor(ctx, in, info, handler)
}
var _Auth_serviceDesc = grpc.ServiceDesc{
ServiceName: "pbAuth.Auth",
HandlerType: (*AuthServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "UserRegister",
Handler: _Auth_UserRegister_Handler,
},
{
MethodName: "UserToken",
Handler: _Auth_UserToken_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "auth/auth.proto",
}
func init() { proto.RegisterFile("auth/auth.proto", fileDescriptor_auth_88965eda3ab7f34d) }
var fileDescriptor_auth_88965eda3ab7f34d = []byte{
// 369 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x9c, 0x52, 0x4d, 0x4b, 0xc3, 0x40,
0x10, 0x25, 0xf6, 0xc3, 0x76, 0x6a, 0xa9, 0x2c, 0x55, 0x43, 0x04, 0xa9, 0x39, 0xf5, 0x94, 0x40,
0x3d, 0x28, 0x08, 0x42, 0xad, 0x16, 0x7a, 0x28, 0x95, 0xa5, 0x5e, 0xbc, 0x84, 0x94, 0x6e, 0xdb,
0x90, 0x26, 0xbb, 0xee, 0xa6, 0x56, 0xf0, 0xe8, 0xc5, 0x9f, 0x2d, 0xbb, 0xf9, 0x70, 0xad, 0x3d,
0x79, 0x49, 0x98, 0x79, 0x2f, 0xf3, 0xde, 0x9b, 0x0c, 0xb4, 0xfc, 0x4d, 0xb2, 0x72, 0xe5, 0xc3,
0x61, 0x9c, 0x26, 0x14, 0x55, 0xd9, 0xac, 0xbf, 0x49, 0x56, 0xd6, 0xe5, 0x84, 0x91, 0xd8, 0x1b,
0x8d, 0x5d, 0x16, 0x2e, 0x5d, 0x05, 0xb9, 0x62, 0x1e, 0x7a, 0x5b, 0xe1, 0x6e, 0x45, 0x4a, 0xb5,
0xef, 0x00, 0x06, 0x34, 0x8a, 0x68, 0x8c, 0x89, 0x60, 0xc8, 0x84, 0x43, 0xc2, 0xf9, 0x80, 0xce,
0x89, 0x69, 0x74, 0x8c, 0x6e, 0x05, 0xe7, 0x25, 0x3a, 0x85, 0x2a, 0xe1, 0x7c, 0x2c, 0x96, 0xe6,
0x41, 0xc7, 0xe8, 0xd6, 0x71, 0x56, 0xd9, 0x6b, 0x68, 0x3d, 0x0b, 0xc2, 0x31, 0x59, 0x06, 0x22,
0x91, 0xef, 0x57, 0x74, 0x0d, 0x35, 0xd9, 0x1a, 0xc5, 0x0b, 0xaa, 0xa6, 0x34, 0x7a, 0xe7, 0x8e,
0x20, 0xfc, 0x8d, 0x70, 0xcf, 0x67, 0x81, 0xc7, 0x7c, 0xee, 0x47, 0xc2, 0xc9, 0x29, 0xb8, 0x20,
0xa3, 0x0e, 0x34, 0x26, 0x8c, 0x70, 0x3f, 0x09, 0x68, 0x3c, 0x7a, 0xc8, 0x84, 0xf4, 0x96, 0x3d,
0x84, 0xe3, 0xdf, 0x6a, 0x82, 0xa1, 0x9e, 0x9e, 0x20, 0x13, 0x44, 0x4e, 0xba, 0x01, 0xe7, 0x07,
0xc1, 0x1a, 0xcb, 0xfe, 0x32, 0xe0, 0x48, 0x0e, 0x9a, 0xd2, 0x90, 0xc4, 0xd2, 0xb3, 0x05, 0xb5,
0xa7, 0xb5, 0x9f, 0x2c, 0x28, 0x8f, 0xb2, 0xe4, 0x45, 0x8d, 0x2e, 0x00, 0x86, 0x9c, 0x46, 0xca,
0x66, 0xee, 0x4a, 0xeb, 0xc8, 0x6f, 0x27, 0x2c, 0x43, 0x4b, 0x0a, 0x2d, 0xea, 0xdd, 0x48, 0xe5,
0xbf, 0x91, 0x3e, 0xa0, 0xa9, 0x39, 0xf9, 0x5f, 0x1e, 0xd4, 0x86, 0x8a, 0x1a, 0x90, 0xb9, 0x4b,
0x0b, 0x29, 0xfe, 0xf8, 0xce, 0x02, 0x4e, 0xe6, 0xd3, 0x20, 0x22, 0xca, 0x5b, 0x09, 0xeb, 0xad,
0xde, 0xa7, 0x01, 0x65, 0x39, 0x17, 0xf5, 0xd3, 0x7d, 0xe4, 0x8b, 0x45, 0x67, 0xb9, 0xe0, 0xce,
0xcf, 0xb5, 0xcc, 0xfd, 0x80, 0x60, 0xe8, 0x06, 0xea, 0x45, 0x10, 0xd4, 0xd6, 0x69, 0xf9, 0x96,
0xad, 0x93, 0x3d, 0x5d, 0xc1, 0xee, 0x5b, 0x2f, 0x4d, 0x47, 0x9d, 0xef, 0x6d, 0x0a, 0xcf, 0xaa,
0xea, 0x36, 0xaf, 0xbe, 0x03, 0x00, 0x00, 0xff, 0xff, 0x1b, 0x20, 0x74, 0x9f, 0xd9, 0x02, 0x00,
0x00,
}
+36
View File
@@ -0,0 +1,36 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
package pbAuth;
option go_package = "./auth;pbAuth";
message CommonResp{
int32 errCode = 1;
string errMsg = 2;
}
message UserRegisterReq {
server_api_params.UserInfo UserInfo = 1;
string OperationID = 2;
}
message UserRegisterResp {
CommonResp CommonResp = 1;
}
message UserTokenReq {
int32 Platform = 1;
string FromUserID = 2;
string OpUserID = 3;
string OperationID = 4;
}
message UserTokenResp {
CommonResp CommonResp = 1;
string Token = 2;
int64 ExpiredTime = 3;
}
service Auth {
rpc UserRegister(UserRegisterReq) returns(UserRegisterResp);
rpc UserToken(UserTokenReq) returns(UserTokenResp);
}
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
source ./proto_dir.cfg
for ((i = 0; i < ${#all_proto[*]}; i++)); do
proto=${all_proto[$i]}
protoc -I ../../../ -I ./ --go_out=plugins=grpc:. $proto
s=`echo $proto | sed 's/ //g'`
v=${s//proto/pb.go}
protoc-go-inject-tag -input=./$v
echo "protoc --go_out=plugins=grpc:." $proto
done
echo "proto file generate success..."
+5
View File
@@ -0,0 +1,5 @@
syntax = "proto3";
package base;
+650
View File
@@ -0,0 +1,650 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: chat/chat.proto
package pbChat // import "./chat"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import sdk_ws "Open_IM/pkg/proto/sdk_ws"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type MsgDataToMQ struct {
Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=operationID" json:"operationID,omitempty"`
MsgData *sdk_ws.MsgData `protobuf:"bytes,3,opt,name=msgData" json:"msgData,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *MsgDataToMQ) Reset() { *m = MsgDataToMQ{} }
func (m *MsgDataToMQ) String() string { return proto.CompactTextString(m) }
func (*MsgDataToMQ) ProtoMessage() {}
func (*MsgDataToMQ) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{0}
}
func (m *MsgDataToMQ) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgDataToMQ.Unmarshal(m, b)
}
func (m *MsgDataToMQ) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgDataToMQ.Marshal(b, m, deterministic)
}
func (dst *MsgDataToMQ) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgDataToMQ.Merge(dst, src)
}
func (m *MsgDataToMQ) XXX_Size() int {
return xxx_messageInfo_MsgDataToMQ.Size(m)
}
func (m *MsgDataToMQ) XXX_DiscardUnknown() {
xxx_messageInfo_MsgDataToMQ.DiscardUnknown(m)
}
var xxx_messageInfo_MsgDataToMQ proto.InternalMessageInfo
func (m *MsgDataToMQ) GetToken() string {
if m != nil {
return m.Token
}
return ""
}
func (m *MsgDataToMQ) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *MsgDataToMQ) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
type MsgDataToDB struct {
MsgData *sdk_ws.MsgData `protobuf:"bytes,1,opt,name=msgData" json:"msgData,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=operationID" json:"operationID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *MsgDataToDB) Reset() { *m = MsgDataToDB{} }
func (m *MsgDataToDB) String() string { return proto.CompactTextString(m) }
func (*MsgDataToDB) ProtoMessage() {}
func (*MsgDataToDB) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{1}
}
func (m *MsgDataToDB) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_MsgDataToDB.Unmarshal(m, b)
}
func (m *MsgDataToDB) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_MsgDataToDB.Marshal(b, m, deterministic)
}
func (dst *MsgDataToDB) XXX_Merge(src proto.Message) {
xxx_messageInfo_MsgDataToDB.Merge(dst, src)
}
func (m *MsgDataToDB) XXX_Size() int {
return xxx_messageInfo_MsgDataToDB.Size(m)
}
func (m *MsgDataToDB) XXX_DiscardUnknown() {
xxx_messageInfo_MsgDataToDB.DiscardUnknown(m)
}
var xxx_messageInfo_MsgDataToDB proto.InternalMessageInfo
func (m *MsgDataToDB) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
func (m *MsgDataToDB) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
type PushMsgDataToMQ struct {
OperationID string `protobuf:"bytes,1,opt,name=OperationID" json:"OperationID,omitempty"`
MsgData *sdk_ws.MsgData `protobuf:"bytes,2,opt,name=msgData" json:"msgData,omitempty"`
PushToUserID string `protobuf:"bytes,3,opt,name=pushToUserID" json:"pushToUserID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PushMsgDataToMQ) Reset() { *m = PushMsgDataToMQ{} }
func (m *PushMsgDataToMQ) String() string { return proto.CompactTextString(m) }
func (*PushMsgDataToMQ) ProtoMessage() {}
func (*PushMsgDataToMQ) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{2}
}
func (m *PushMsgDataToMQ) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PushMsgDataToMQ.Unmarshal(m, b)
}
func (m *PushMsgDataToMQ) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PushMsgDataToMQ.Marshal(b, m, deterministic)
}
func (dst *PushMsgDataToMQ) XXX_Merge(src proto.Message) {
xxx_messageInfo_PushMsgDataToMQ.Merge(dst, src)
}
func (m *PushMsgDataToMQ) XXX_Size() int {
return xxx_messageInfo_PushMsgDataToMQ.Size(m)
}
func (m *PushMsgDataToMQ) XXX_DiscardUnknown() {
xxx_messageInfo_PushMsgDataToMQ.DiscardUnknown(m)
}
var xxx_messageInfo_PushMsgDataToMQ proto.InternalMessageInfo
func (m *PushMsgDataToMQ) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *PushMsgDataToMQ) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
func (m *PushMsgDataToMQ) GetPushToUserID() string {
if m != nil {
return m.PushToUserID
}
return ""
}
// message PullMessageReq {
// string UserID = 1;
// int64 SeqBegin = 2;
// int64 SeqEnd = 3;
// string OperationID = 4;
// }
//
// message PullMessageResp {
// int32 ErrCode = 1;
// string ErrMsg = 2;
// int64 MaxSeq = 3;
// int64 MinSeq = 4;
// repeated GatherFormat SingleUserMsg = 5;
// repeated GatherFormat GroupUserMsg = 6;
// }
// message PullMessageBySeqListReq{
// string UserID = 1;
// string OperationID = 2;
// repeated int64 seqList =3;
// }
type GetMaxAndMinSeqReq struct {
UserID string `protobuf:"bytes,1,opt,name=UserID" json:"UserID,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=OperationID" json:"OperationID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetMaxAndMinSeqReq) Reset() { *m = GetMaxAndMinSeqReq{} }
func (m *GetMaxAndMinSeqReq) String() string { return proto.CompactTextString(m) }
func (*GetMaxAndMinSeqReq) ProtoMessage() {}
func (*GetMaxAndMinSeqReq) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{3}
}
func (m *GetMaxAndMinSeqReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetMaxAndMinSeqReq.Unmarshal(m, b)
}
func (m *GetMaxAndMinSeqReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetMaxAndMinSeqReq.Marshal(b, m, deterministic)
}
func (dst *GetMaxAndMinSeqReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetMaxAndMinSeqReq.Merge(dst, src)
}
func (m *GetMaxAndMinSeqReq) XXX_Size() int {
return xxx_messageInfo_GetMaxAndMinSeqReq.Size(m)
}
func (m *GetMaxAndMinSeqReq) XXX_DiscardUnknown() {
xxx_messageInfo_GetMaxAndMinSeqReq.DiscardUnknown(m)
}
var xxx_messageInfo_GetMaxAndMinSeqReq proto.InternalMessageInfo
func (m *GetMaxAndMinSeqReq) GetUserID() string {
if m != nil {
return m.UserID
}
return ""
}
func (m *GetMaxAndMinSeqReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
type GetMaxAndMinSeqResp struct {
ErrCode int32 `protobuf:"varint,1,opt,name=ErrCode" json:"ErrCode,omitempty"`
ErrMsg string `protobuf:"bytes,2,opt,name=ErrMsg" json:"ErrMsg,omitempty"`
MaxSeq uint32 `protobuf:"varint,3,opt,name=MaxSeq" json:"MaxSeq,omitempty"`
MinSeq uint32 `protobuf:"varint,4,opt,name=MinSeq" json:"MinSeq,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetMaxAndMinSeqResp) Reset() { *m = GetMaxAndMinSeqResp{} }
func (m *GetMaxAndMinSeqResp) String() string { return proto.CompactTextString(m) }
func (*GetMaxAndMinSeqResp) ProtoMessage() {}
func (*GetMaxAndMinSeqResp) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{4}
}
func (m *GetMaxAndMinSeqResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetMaxAndMinSeqResp.Unmarshal(m, b)
}
func (m *GetMaxAndMinSeqResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetMaxAndMinSeqResp.Marshal(b, m, deterministic)
}
func (dst *GetMaxAndMinSeqResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetMaxAndMinSeqResp.Merge(dst, src)
}
func (m *GetMaxAndMinSeqResp) XXX_Size() int {
return xxx_messageInfo_GetMaxAndMinSeqResp.Size(m)
}
func (m *GetMaxAndMinSeqResp) XXX_DiscardUnknown() {
xxx_messageInfo_GetMaxAndMinSeqResp.DiscardUnknown(m)
}
var xxx_messageInfo_GetMaxAndMinSeqResp proto.InternalMessageInfo
func (m *GetMaxAndMinSeqResp) GetErrCode() int32 {
if m != nil {
return m.ErrCode
}
return 0
}
func (m *GetMaxAndMinSeqResp) GetErrMsg() string {
if m != nil {
return m.ErrMsg
}
return ""
}
func (m *GetMaxAndMinSeqResp) GetMaxSeq() uint32 {
if m != nil {
return m.MaxSeq
}
return 0
}
func (m *GetMaxAndMinSeqResp) GetMinSeq() uint32 {
if m != nil {
return m.MinSeq
}
return 0
}
type SendMsgReq struct {
Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=operationID" json:"operationID,omitempty"`
MsgData *sdk_ws.MsgData `protobuf:"bytes,3,opt,name=msgData" json:"msgData,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SendMsgReq) Reset() { *m = SendMsgReq{} }
func (m *SendMsgReq) String() string { return proto.CompactTextString(m) }
func (*SendMsgReq) ProtoMessage() {}
func (*SendMsgReq) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{5}
}
func (m *SendMsgReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SendMsgReq.Unmarshal(m, b)
}
func (m *SendMsgReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SendMsgReq.Marshal(b, m, deterministic)
}
func (dst *SendMsgReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_SendMsgReq.Merge(dst, src)
}
func (m *SendMsgReq) XXX_Size() int {
return xxx_messageInfo_SendMsgReq.Size(m)
}
func (m *SendMsgReq) XXX_DiscardUnknown() {
xxx_messageInfo_SendMsgReq.DiscardUnknown(m)
}
var xxx_messageInfo_SendMsgReq proto.InternalMessageInfo
func (m *SendMsgReq) GetToken() string {
if m != nil {
return m.Token
}
return ""
}
func (m *SendMsgReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *SendMsgReq) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
type SendMsgResp struct {
ErrCode int32 `protobuf:"varint,1,opt,name=errCode" json:"errCode,omitempty"`
ErrMsg string `protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"`
ServerMsgID string `protobuf:"bytes,4,opt,name=serverMsgID" json:"serverMsgID,omitempty"`
ClientMsgID string `protobuf:"bytes,5,opt,name=clientMsgID" json:"clientMsgID,omitempty"`
SendTime int64 `protobuf:"varint,6,opt,name=sendTime" json:"sendTime,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SendMsgResp) Reset() { *m = SendMsgResp{} }
func (m *SendMsgResp) String() string { return proto.CompactTextString(m) }
func (*SendMsgResp) ProtoMessage() {}
func (*SendMsgResp) Descriptor() ([]byte, []int) {
return fileDescriptor_chat_83f286704599d5b1, []int{6}
}
func (m *SendMsgResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SendMsgResp.Unmarshal(m, b)
}
func (m *SendMsgResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SendMsgResp.Marshal(b, m, deterministic)
}
func (dst *SendMsgResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_SendMsgResp.Merge(dst, src)
}
func (m *SendMsgResp) XXX_Size() int {
return xxx_messageInfo_SendMsgResp.Size(m)
}
func (m *SendMsgResp) XXX_DiscardUnknown() {
xxx_messageInfo_SendMsgResp.DiscardUnknown(m)
}
var xxx_messageInfo_SendMsgResp proto.InternalMessageInfo
func (m *SendMsgResp) GetErrCode() int32 {
if m != nil {
return m.ErrCode
}
return 0
}
func (m *SendMsgResp) GetErrMsg() string {
if m != nil {
return m.ErrMsg
}
return ""
}
func (m *SendMsgResp) GetServerMsgID() string {
if m != nil {
return m.ServerMsgID
}
return ""
}
func (m *SendMsgResp) GetClientMsgID() string {
if m != nil {
return m.ClientMsgID
}
return ""
}
func (m *SendMsgResp) GetSendTime() int64 {
if m != nil {
return m.SendTime
}
return 0
}
func init() {
proto.RegisterType((*MsgDataToMQ)(nil), "pbChat.MsgDataToMQ")
proto.RegisterType((*MsgDataToDB)(nil), "pbChat.MsgDataToDB")
proto.RegisterType((*PushMsgDataToMQ)(nil), "pbChat.PushMsgDataToMQ")
proto.RegisterType((*GetMaxAndMinSeqReq)(nil), "pbChat.GetMaxAndMinSeqReq")
proto.RegisterType((*GetMaxAndMinSeqResp)(nil), "pbChat.GetMaxAndMinSeqResp")
proto.RegisterType((*SendMsgReq)(nil), "pbChat.SendMsgReq")
proto.RegisterType((*SendMsgResp)(nil), "pbChat.SendMsgResp")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// Client API for Chat service
type ChatClient interface {
GetMaxAndMinSeq(ctx context.Context, in *GetMaxAndMinSeqReq, opts ...grpc.CallOption) (*GetMaxAndMinSeqResp, error)
PullMessageBySeqList(ctx context.Context, in *sdk_ws.PullMessageBySeqListReq, opts ...grpc.CallOption) (*sdk_ws.PullMessageBySeqListResp, error)
SendMsg(ctx context.Context, in *SendMsgReq, opts ...grpc.CallOption) (*SendMsgResp, error)
DelMsgList(ctx context.Context, in *sdk_ws.DelMsgListReq, opts ...grpc.CallOption) (*sdk_ws.DelMsgListResp, error)
}
type chatClient struct {
cc *grpc.ClientConn
}
func NewChatClient(cc *grpc.ClientConn) ChatClient {
return &chatClient{cc}
}
func (c *chatClient) GetMaxAndMinSeq(ctx context.Context, in *GetMaxAndMinSeqReq, opts ...grpc.CallOption) (*GetMaxAndMinSeqResp, error) {
out := new(GetMaxAndMinSeqResp)
err := grpc.Invoke(ctx, "/pbChat.Chat/GetMaxAndMinSeq", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatClient) PullMessageBySeqList(ctx context.Context, in *sdk_ws.PullMessageBySeqListReq, opts ...grpc.CallOption) (*sdk_ws.PullMessageBySeqListResp, error) {
out := new(sdk_ws.PullMessageBySeqListResp)
err := grpc.Invoke(ctx, "/pbChat.Chat/PullMessageBySeqList", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatClient) SendMsg(ctx context.Context, in *SendMsgReq, opts ...grpc.CallOption) (*SendMsgResp, error) {
out := new(SendMsgResp)
err := grpc.Invoke(ctx, "/pbChat.Chat/SendMsg", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *chatClient) DelMsgList(ctx context.Context, in *sdk_ws.DelMsgListReq, opts ...grpc.CallOption) (*sdk_ws.DelMsgListResp, error) {
out := new(sdk_ws.DelMsgListResp)
err := grpc.Invoke(ctx, "/pbChat.Chat/DelMsgList", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for Chat service
type ChatServer interface {
GetMaxAndMinSeq(context.Context, *GetMaxAndMinSeqReq) (*GetMaxAndMinSeqResp, error)
PullMessageBySeqList(context.Context, *sdk_ws.PullMessageBySeqListReq) (*sdk_ws.PullMessageBySeqListResp, error)
SendMsg(context.Context, *SendMsgReq) (*SendMsgResp, error)
DelMsgList(context.Context, *sdk_ws.DelMsgListReq) (*sdk_ws.DelMsgListResp, error)
}
func RegisterChatServer(s *grpc.Server, srv ChatServer) {
s.RegisterService(&_Chat_serviceDesc, srv)
}
func _Chat_GetMaxAndMinSeq_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetMaxAndMinSeqReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServer).GetMaxAndMinSeq(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbChat.Chat/GetMaxAndMinSeq",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServer).GetMaxAndMinSeq(ctx, req.(*GetMaxAndMinSeqReq))
}
return interceptor(ctx, in, info, handler)
}
func _Chat_PullMessageBySeqList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sdk_ws.PullMessageBySeqListReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServer).PullMessageBySeqList(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbChat.Chat/PullMessageBySeqList",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServer).PullMessageBySeqList(ctx, req.(*sdk_ws.PullMessageBySeqListReq))
}
return interceptor(ctx, in, info, handler)
}
func _Chat_SendMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SendMsgReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServer).SendMsg(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbChat.Chat/SendMsg",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServer).SendMsg(ctx, req.(*SendMsgReq))
}
return interceptor(ctx, in, info, handler)
}
func _Chat_DelMsgList_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(sdk_ws.DelMsgListReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ChatServer).DelMsgList(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/pbChat.Chat/DelMsgList",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ChatServer).DelMsgList(ctx, req.(*sdk_ws.DelMsgListReq))
}
return interceptor(ctx, in, info, handler)
}
var _Chat_serviceDesc = grpc.ServiceDesc{
ServiceName: "pbChat.Chat",
HandlerType: (*ChatServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetMaxAndMinSeq",
Handler: _Chat_GetMaxAndMinSeq_Handler,
},
{
MethodName: "PullMessageBySeqList",
Handler: _Chat_PullMessageBySeqList_Handler,
},
{
MethodName: "SendMsg",
Handler: _Chat_SendMsg_Handler,
},
{
MethodName: "DelMsgList",
Handler: _Chat_DelMsgList_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "chat/chat.proto",
}
func init() { proto.RegisterFile("chat/chat.proto", fileDescriptor_chat_83f286704599d5b1) }
var fileDescriptor_chat_83f286704599d5b1 = []byte{
// 507 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x54, 0xcd, 0x6e, 0xda, 0x40,
0x10, 0x96, 0x49, 0x80, 0x32, 0x34, 0x42, 0xda, 0x44, 0x95, 0xe5, 0x5e, 0x1c, 0x9f, 0x50, 0x2b,
0x19, 0x89, 0xf6, 0xd6, 0x53, 0x89, 0xa3, 0x8a, 0xaa, 0xdb, 0x24, 0x86, 0x5e, 0x7a, 0x41, 0x9b,
0x30, 0x32, 0x16, 0x60, 0x2f, 0x3b, 0xa6, 0xa4, 0xed, 0x33, 0xf4, 0x19, 0xfa, 0x3e, 0x7d, 0xaa,
0xca, 0xbb, 0x26, 0x98, 0x40, 0x15, 0x4e, 0xbd, 0x58, 0x9a, 0x6f, 0x3e, 0x7f, 0x3f, 0xeb, 0x1f,
0x68, 0xdd, 0x4d, 0x44, 0xd6, 0xc9, 0x2f, 0xbe, 0x54, 0x69, 0x96, 0xb2, 0x9a, 0xbc, 0xbd, 0x98,
0x88, 0xcc, 0x39, 0xbf, 0x92, 0x98, 0x8c, 0xfa, 0xbc, 0x23, 0xa7, 0x51, 0x47, 0xaf, 0x3a, 0x34,
0x9e, 0x8e, 0x56, 0xd4, 0x59, 0x91, 0xa1, 0x7a, 0x3f, 0xa1, 0xc9, 0x29, 0x0a, 0x44, 0x26, 0x86,
0x29, 0xbf, 0x61, 0x67, 0x50, 0xcd, 0xd2, 0x29, 0x26, 0xb6, 0xe5, 0x5a, 0xed, 0x46, 0x68, 0x06,
0xe6, 0x42, 0x33, 0x95, 0xa8, 0x44, 0x16, 0xa7, 0x49, 0x3f, 0xb0, 0x2b, 0x7a, 0x57, 0x86, 0xd8,
0x5b, 0xa8, 0xcf, 0x8d, 0x8c, 0x7d, 0xe4, 0x5a, 0xed, 0x66, 0xd7, 0xf1, 0x09, 0xd5, 0x37, 0x54,
0x23, 0x21, 0xe3, 0x91, 0x14, 0x4a, 0xcc, 0xc9, 0x2f, 0x8c, 0xc2, 0x35, 0xd5, 0xc3, 0x92, 0x79,
0xd0, 0x2b, 0x8b, 0x58, 0x07, 0x8b, 0x3c, 0x1d, 0xce, 0xfb, 0x65, 0x41, 0xeb, 0x7a, 0x49, 0x93,
0x72, 0x51, 0x17, 0x9a, 0x57, 0xa5, 0xbb, 0x4c, 0xdd, 0x32, 0x54, 0x4e, 0x53, 0x39, 0x3c, 0x8d,
0x07, 0xcf, 0xe5, 0x92, 0x26, 0xc3, 0xf4, 0x0b, 0xa1, 0xea, 0x07, 0xfa, 0x34, 0x1a, 0xe1, 0x16,
0xe6, 0x7d, 0x06, 0xf6, 0x01, 0x33, 0x2e, 0xee, 0xdf, 0x27, 0x63, 0x1e, 0x27, 0x03, 0x5c, 0x84,
0xb8, 0x60, 0x2f, 0xa0, 0x56, 0xdc, 0x63, 0xc2, 0x14, 0xd3, 0xe3, 0xa4, 0x95, 0x9d, 0xa4, 0xde,
0x0a, 0x4e, 0x77, 0xf4, 0x48, 0x32, 0x1b, 0xea, 0x97, 0x4a, 0x5d, 0xa4, 0x63, 0xd4, 0x8a, 0xd5,
0x70, 0x3d, 0xe6, 0x56, 0x97, 0x4a, 0x71, 0x8a, 0x0a, 0xb5, 0x62, 0xca, 0x71, 0x2e, 0xee, 0x07,
0xb8, 0xd0, 0xb1, 0x4f, 0xc2, 0x62, 0xd2, 0xb8, 0xd6, 0xb5, 0x8f, 0x0b, 0x5c, 0x4f, 0xde, 0x0f,
0x80, 0x01, 0x26, 0x63, 0x4e, 0x51, 0x5e, 0xe0, 0xff, 0xbe, 0x3b, 0xbf, 0x2d, 0x68, 0x3e, 0x98,
0x9b, 0xb6, 0xb8, 0xdd, 0x16, 0x37, 0x6d, 0x71, 0xab, 0xad, 0x99, 0xf2, 0x64, 0xc6, 0x87, 0x53,
0xd4, 0x0f, 0x74, 0xb5, 0x46, 0x58, 0x86, 0x72, 0xc6, 0xdd, 0x2c, 0xc6, 0x24, 0x33, 0x8c, 0xaa,
0x61, 0x94, 0x20, 0xe6, 0xc0, 0x33, 0xc2, 0x64, 0x3c, 0x8c, 0xe7, 0x68, 0xd7, 0x5c, 0xab, 0x7d,
0x14, 0x3e, 0xcc, 0xdd, 0x3f, 0x15, 0x38, 0xce, 0x3f, 0x43, 0xf6, 0x11, 0x5a, 0x8f, 0x9e, 0x0f,
0x73, 0x7c, 0xf3, 0x89, 0xfa, 0xbb, 0x2f, 0x82, 0xf3, 0xf2, 0x9f, 0x3b, 0x92, 0x2c, 0x85, 0xb3,
0xeb, 0xe5, 0x6c, 0xc6, 0x91, 0x48, 0x44, 0xd8, 0xfb, 0x3e, 0xc0, 0xc5, 0xa7, 0x98, 0x32, 0xf6,
0x6a, 0xcf, 0x99, 0xed, 0x23, 0xe6, 0x06, 0xaf, 0x0f, 0xe6, 0x92, 0x64, 0x5d, 0xa8, 0x17, 0xc7,
0xcc, 0xd8, 0x3a, 0xd8, 0xe6, 0xa1, 0x3b, 0xa7, 0x3b, 0x18, 0x49, 0x76, 0x03, 0x10, 0xe0, 0x8c,
0x53, 0xa4, 0xa3, 0xb9, 0x7b, 0xec, 0x36, 0xeb, 0x5c, 0xe4, 0xfc, 0x09, 0x06, 0xc9, 0x5e, 0xeb,
0xeb, 0x89, 0xaf, 0x7f, 0x71, 0xef, 0x8c, 0xdf, 0x6d, 0x4d, 0xff, 0xbf, 0xde, 0xfc, 0x0d, 0x00,
0x00, 0xff, 0xff, 0x6f, 0x9d, 0x6f, 0xa0, 0xfd, 0x04, 0x00, 0x00,
}
+82
View File
@@ -0,0 +1,82 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./chat;pbChat";
package pbChat;
message MsgDataToMQ{
string token =1;
string operationID = 2;
server_api_params.MsgData msgData = 3;
}
message MsgDataToDB {
server_api_params.MsgData msgData = 1;
string operationID = 2;
}
message PushMsgDataToMQ{
string OperationID = 1;
server_api_params.MsgData msgData = 2;
string pushToUserID = 3;
}
//message PullMessageReq {
// string UserID = 1;
// int64 SeqBegin = 2;
// int64 SeqEnd = 3;
// string OperationID = 4;
//}
//
//message PullMessageResp {
// int32 ErrCode = 1;
// string ErrMsg = 2;
// int64 MaxSeq = 3;
// int64 MinSeq = 4;
// repeated GatherFormat SingleUserMsg = 5;
// repeated GatherFormat GroupUserMsg = 6;
//}
//message PullMessageBySeqListReq{
// string UserID = 1;
// string OperationID = 2;
// repeated int64 seqList =3;
//}
message GetMaxAndMinSeqReq {
string UserID = 1;
string OperationID = 2;
}
message GetMaxAndMinSeqResp {
int32 ErrCode = 1;
string ErrMsg = 2;
uint32 MaxSeq = 3;
uint32 MinSeq = 4;
}
message SendMsgReq {
string token =1;
string operationID = 2;
server_api_params.MsgData msgData = 3;
}
message SendMsgResp {
int32 errCode = 1;
string errMsg = 2;
string serverMsgID = 4;
string clientMsgID = 5;
int64 sendTime = 6;
}
service Chat {
rpc GetMaxAndMinSeq(GetMaxAndMinSeqReq) returns(GetMaxAndMinSeqResp);
rpc PullMessageBySeqList(server_api_params.PullMessageBySeqListReq) returns(server_api_params.PullMessageBySeqListResp);
rpc SendMsg(SendMsgReq) returns(SendMsgResp);
rpc DelMsgList(server_api_params.DelMsgListReq) returns(server_api_params.DelMsgListResp);
}
File diff suppressed because it is too large Load Diff
+169
View File
@@ -0,0 +1,169 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./friend;friend";
package friend;
message CommonResp{
int32 errCode = 1;
string errMsg = 2;
}
message CommID{
string OpUserID = 1;
string OperationID = 2;
string ToUserID = 4;
string FromUserID = 5;
}
message GetFriendsInfoReq{
CommID CommID = 1;
}
message GetFriendInfoResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.FriendInfo FriendInfoList = 3;
// int32 IsBlack = 4;
}
message AddFriendReq{
CommID CommID = 1;
string ReqMsg = 2;
}
message AddFriendResp{
CommonResp CommonResp = 1;
}
message ImportFriendReq{
repeated string FriendUserIDList = 1;
string OperationID = 2;
string FromUserID = 3;
string OpUserID = 4;
}
message UserIDResult{
string UserID = 1;
int32 Result = 2;
}
message ImportFriendResp{
CommonResp CommonResp = 1;
repeated UserIDResult UserIDResultList = 2;
}
message GetFriendApplyListReq{
CommID CommID = 1;
}
message GetFriendApplyListResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.FriendRequest FriendRequestList = 3;
}
message GetFriendListReq{
CommID CommID = 1;
}
message GetFriendListResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.FriendInfo FriendInfoList = 3;
}
message AddBlacklistReq{
CommID CommID = 1;
}
message AddBlacklistResp{
CommonResp CommonResp = 1;
}
message RemoveBlacklistReq{
CommID CommID = 1;
}
message RemoveBlacklistResp{
CommonResp CommonResp = 1;
}
message GetBlacklistReq{
CommID CommID = 1;
}
message GetBlacklistResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.PublicUserInfo BlackUserInfoList = 3;
}
message IsFriendReq{
CommID CommID = 1;
}
message IsFriendResp{
int32 ErrCode = 1;
string ErrMsg = 2;
bool Response = 3;
}
message IsInBlackListReq{
CommID CommID = 1;
}
message IsInBlackListResp{
int32 ErrCode = 1;
string ErrMsg = 2;
bool Response = 3;
}
message DeleteFriendReq{
CommID CommID = 1;
}
message DeleteFriendResp{
CommonResp CommonResp = 1;
}
//process
message AddFriendResponseReq{
CommID CommID = 1;
int32 handleResult = 2;
string handleMsg = 3;
}
message AddFriendResponseResp{
CommonResp CommonResp = 1;
}
message SetFriendRemarkReq{
CommID CommID = 1;
string Remark = 2;
}
message SetFriendRemarkResp{
CommonResp CommonResp = 1;
}
message GetSelfApplyListReq{
CommID CommID = 1;
}
message GetSelfApplyListResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.FriendRequest FriendRequestList = 3;
}
service friend{
// rpc getFriendsInfo(GetFriendsInfoReq) returns(GetFriendInfoResp);
rpc addFriend(AddFriendReq) returns(AddFriendResp);
rpc getFriendApplyList(GetFriendApplyListReq) returns(GetFriendApplyListResp);
rpc getSelfApplyList(GetSelfApplyListReq) returns(GetSelfApplyListResp);
rpc getFriendList(GetFriendListReq) returns(GetFriendListResp);
rpc addBlacklist(AddBlacklistReq) returns(AddBlacklistResp);
rpc removeBlacklist(RemoveBlacklistReq) returns(RemoveBlacklistResp);
rpc isFriend(IsFriendReq) returns(IsFriendResp);
rpc isInBlackList(IsInBlackListReq) returns(IsInBlackListResp);
rpc getBlacklist(GetBlacklistReq) returns(GetBlacklistResp);
rpc deleteFriend(DeleteFriendReq) returns(DeleteFriendResp);
rpc addFriendResponse(AddFriendResponseReq) returns(AddFriendResponseResp);
rpc setFriendRemark(SetFriendRemarkReq) returns(SetFriendRemarkResp);
rpc importFriend(ImportFriendReq) returns(ImportFriendResp);
}
File diff suppressed because it is too large Load Diff
+423
View File
@@ -0,0 +1,423 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./group;group";
package group;
message CommonResp{
int32 ErrCode = 1;
string ErrMsg = 2;
}
message GroupAddMemberInfo{
string UserID = 1;
int32 RoleLevel = 2;
}
message CreateGroupReq{
repeated GroupAddMemberInfo InitMemberList = 1;
server_api_params.GroupInfo GroupInfo = 2;
string OperationID = 3;
string OpUserID = 4; //app manager or group owner
string OwnerUserID = 5; //owner
}
message CreateGroupResp{
int32 ErrCode = 1;
string ErrMsg = 2;
server_api_params.GroupInfo GroupInfo = 3;
}
message GetGroupsInfoReq{
repeated string GroupIDList = 1;
string OperationID = 2;
string OpUserID = 3; //No verification permission
}
message GetGroupsInfoResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.GroupInfo GroupInfoList = 3;
}
message SetGroupInfoReq{
server_api_params.GroupInfo GroupInfo = 1;
string OpUserID = 2; //app manager or group owner
string OperationID = 3;
}
message SetGroupInfoResp{
CommonResp CommonResp = 1;
}
message GetGroupApplicationListReq {
string OpUserID = 1; //app manager or group owner(manager)
string OperationID = 2;
string FromUserID = 3; //owner or manager
}
message GetGroupApplicationListResp {
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.GroupRequest GroupRequestList = 3;
}
message GetUserReqApplicationListReq{
string UserID = 1;
string OpUserID = 2;
string OperationID = 3;
}
message GetUserReqApplicationListResp{
CommonResp CommonResp = 1;
repeated server_api_params.GroupRequest GroupRequestList = 2;
}
message TransferGroupOwnerReq {
string GroupID = 1;
string OldOwnerUserID = 2;
string NewOwnerUserID = 3;
string OperationID = 4;
string OpUserID = 5; //app manager or group owner
}
message TransferGroupOwnerResp{
CommonResp CommonResp = 1;
}
message JoinGroupReq{
string GroupID = 1;
string ReqMessage = 2;
string OpUserID = 3;
string OperationID = 4;
}
message JoinGroupResp{
CommonResp CommonResp = 1;
}
message GroupApplicationResponseReq{
string OperationID = 1;
string OpUserID = 2;
string GroupID = 3;
string FromUserID = 4; //
string HandledMsg = 5;
int32 HandleResult = 6;
}
message GroupApplicationResponseResp{
CommonResp CommonResp = 1;
}
message QuitGroupReq{
string GroupID = 1;
string OperationID = 2;
string OpUserID = 3;
}
message QuitGroupResp{
CommonResp CommonResp = 1;
}
message GetGroupMemberListReq {
string GroupID = 1;
string OpUserID = 2; //No verification permission
string OperationID = 3;
int32 Filter = 4;
int32 NextSeq = 5;
}
message GetGroupMemberListResp {
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.GroupMemberFullInfo memberList = 3;
int32 nextSeq = 4;
}
message GetGroupMembersInfoReq {
string GroupID = 1;
repeated string memberList = 2;
string OpUserID = 3; //No verification permission
string OperationID = 4;
}
message GetGroupMembersInfoResp {
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.GroupMemberFullInfo memberList = 3;
}
message KickGroupMemberReq {
string GroupID = 1;
repeated string KickedUserIDList = 2;
string Reason = 3;
string OperationID = 5;
string OpUserID = 6; //app manger or group manager
}
message Id2Result {
string UserID = 1;
int32 Result = 2; //0 ok; -1 error
}
message KickGroupMemberResp {
int32 ErrCode = 1;
string ErrMsg = 2;
repeated Id2Result Id2ResultList = 3;
}
message GetJoinedGroupListReq {
string FromUserID = 1;
string operationID = 2;
string OpUserID = 3; //app manager or FromUserID
}
message GetJoinedGroupListResp{
int32 ErrCode = 1;
string ErrMsg = 2;
repeated server_api_params.GroupInfo GroupList = 3;
}
message InviteUserToGroupReq {
string OperationID = 2;
string GroupID = 3;
string Reason = 4;
repeated string InvitedUserIDList = 5;
string OpUserID = 6; //group member or app manager
}
message InviteUserToGroupResp {
int32 ErrCode = 1;
string ErrMsg = 2;
repeated Id2Result Id2ResultList = 3; // 0 ok, -1 error
}
message GetGroupAllMemberReq {
string GroupID = 1;
string OpUserID = 2; //No verification permission
string OperationID = 3;
}
message GetGroupAllMemberResp {
int32 ErrCode = 1;
string ErrMsg = 2;
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;
string OpUserId = 4;
}
message RemoveGroupMembersCMSResp {
repeated string success = 1;
repeated string failed = 2;
}
message AddGroupMembersCMSReq {
string GroupId = 1;
repeated string UserIds = 2;
string OperationId = 3;
string OpUserId = 4;
}
message AddGroupMembersCMSResp {
repeated string success = 1;
repeated string failed = 2;
}
message DismissGroupReq{
string opUserID = 1; //group or app manager
string operationID = 2;
string groupID = 3;
}
message DismissGroupResp{
CommonResp commonResp = 1;
}
message MuteGroupMemberReq{
string opUserID = 1; //group or app manager
string operationID = 2;
string groupID = 3;
string userID = 4;
uint32 mutedSeconds = 5;
}
message MuteGroupMemberResp{
CommonResp commonResp = 1;
}
message CancelMuteGroupMemberReq{
string opUserID = 1; //group or app manager
string operationID = 2;
string groupID = 3;
string userID = 4;
}
message CancelMuteGroupMemberResp{
CommonResp commonResp = 1;
}
message MuteGroupReq{
string opUserID = 1; //group or app manager
string operationID = 2;
string groupID = 3;
}
message MuteGroupResp{
CommonResp commonResp = 1;
}
message CancelMuteGroupReq{
string opUserID = 1; //group or app manager
string operationID = 2;
string groupID = 3;
}
message CancelMuteGroupResp{
CommonResp commonResp = 1;
}
service group{
rpc createGroup(CreateGroupReq) returns(CreateGroupResp);
rpc joinGroup(JoinGroupReq) returns(JoinGroupResp);
rpc quitGroup(QuitGroupReq) returns(QuitGroupResp);
rpc getGroupsInfo(GetGroupsInfoReq) returns(GetGroupsInfoResp);
rpc setGroupInfo(SetGroupInfoReq) returns(SetGroupInfoResp);
rpc getGroupApplicationList(GetGroupApplicationListReq) returns(GetGroupApplicationListResp);
rpc getUserReqApplicationList(GetUserReqApplicationListReq) returns(GetUserReqApplicationListResp);
rpc transferGroupOwner(TransferGroupOwnerReq) returns(TransferGroupOwnerResp);
rpc groupApplicationResponse(GroupApplicationResponseReq) returns(GroupApplicationResponseResp);
rpc getGroupMemberList(GetGroupMemberListReq) returns(GetGroupMemberListResp);
rpc getGroupMembersInfo(GetGroupMembersInfoReq) returns(GetGroupMembersInfoResp);
rpc kickGroupMember(KickGroupMemberReq) returns (KickGroupMemberResp);
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);
rpc DismissGroup(DismissGroupReq) returns(DismissGroupResp);
rpc MuteGroupMember(MuteGroupMemberReq) returns(MuteGroupMemberResp);
rpc CancelMuteGroupMember(CancelMuteGroupMemberReq) returns(CancelMuteGroupMemberResp);
rpc MuteGroup(MuteGroupReq) returns(MuteGroupResp);
rpc CancelMuteGroup(CancelMuteGroupReq) returns(CancelMuteGroupResp);
}
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
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;
int32 ChatLogsNum = 3;
}
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);
}
File diff suppressed because it is too large Load Diff
+263
View File
@@ -0,0 +1,263 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./office;office";
package office;
message CommonResp{
int32 errCode = 1;
string errMsg = 2;
}
message TagUser {
string userID = 1;
string userName = 2;
}
message Tag {
string tagID = 1;
string tagName = 2;
repeated TagUser userList = 3;
}
message GetUserTagsReq{
string userID = 1;
string operationID = 2;
}
message GetUserTagsResp{
CommonResp commonResp = 1;
repeated Tag tags = 2;
}
message CreateTagReq {
string tagName = 1;
string userID = 2;
repeated string userIDList = 3;
string operationID = 4;
}
message CreateTagResp {
CommonResp commonResp = 1;
}
message DeleteTagReq {
string userID = 1;
string tagID = 2;
string operationID = 3;
}
message DeleteTagResp {
CommonResp commonResp = 1;
}
message SetTagReq {
string userID = 1;
string tagID = 2;
string newName = 3;
repeated string increaseUserIDList = 4;
repeated string reduceUserIDList = 5;
string operationID = 6;
}
message SetTagResp {
CommonResp commonResp = 1;
}
message SendMsg2TagReq {
repeated string tagList = 1;
repeated string UserList = 2;
repeated string GroupList = 3;
string sendID = 4;
int32 senderPlatformID = 5;
string content = 6;
string operationID = 7;
}
message SendMsg2TagResp {
CommonResp commonResp = 1;
}
message GetTagSendLogsReq {
server_api_params.RequestPagination Pagination = 1;
string userID = 2;
string operationID = 3;
}
message TagSendLog {
repeated TagUser userList = 1;
string content = 2;
int64 sendTime = 3;
}
message GetTagSendLogsResp {
CommonResp commonResp = 1;
server_api_params.ResponsePagination Pagination = 2;
repeated TagSendLog tagSendLogs = 3;
}
message GetUserTagByIDReq {
string userID = 1;
string tagID = 2;
string operationID = 3;
}
message GetUserTagByIDResp {
CommonResp commonResp = 1;
Tag tag = 2;
}
/// WorkMoment
message LikeUser {
string userID = 1;
string userName = 2;
}
message Comment {
string userID = 1;
string userName = 2;
string replyUserID = 3;
string replyUserName = 4;
string contentID = 5;
string content = 6;
int32 createTime = 7;
}
message WorkMoment {
string workMomentID = 1;
string userID = 2;
string content = 3;
repeated LikeUser likeUsers = 4;
repeated Comment comments = 5;
repeated string whoCanSeeUserIDList = 6;
repeated string whoCantSeeUserIDList = 7;
bool isPrivate = 8;
bool isPublic = 9;
int32 CreateTime = 10;
}
message CreateOneWorkMomentReq {
WorkMoment workMoment = 1;
string userID = 2;
string operationID = 3;
}
message CreateOneWorkMomentResp {
CommonResp commonResp = 1;
}
message DeleteOneWorkMomentReq {
string workMomentID = 1;
string userID = 2;
string operationID = 3;
}
message DeleteOneWorkMomentResp {
CommonResp commonResp = 1;
}
message LikeOneWorkMomentReq {
string userID = 1;
string WorkMomentID = 2;
string operationID = 3;
}
message LikeOneWorkMomentResp {
CommonResp commonResp = 1;
}
message CommentOneWorkMomentReq {
string userID = 1;
string workMomentID = 2;
string replyUserID = 3;
string content = 4;
string operationID = 5;
}
message CommentOneWorkMomentResp {
CommonResp commonResp = 1;
}
message GetUserWorkMomentsReq {
string userID = 1;
server_api_params.RequestPagination Pagination = 2;
string operationID = 3;
}
message GetUserWorkMomentsResp {
CommonResp commonResp = 1;
repeated WorkMoment workMoments = 2;
server_api_params.ResponsePagination Pagination = 3;
}
message GetUserFriendWorkMomentsReq {
string userID = 1;
server_api_params.RequestPagination Pagination = 2;
string operationID = 3;
}
message GetUserFriendWorkMomentsResp {
CommonResp commonResp = 1;
repeated WorkMoment workMoments = 2;
server_api_params.ResponsePagination Pagination = 3;
}
message CommentsMsg {
Comment comment = 1;
string workMomentID = 2;
string content = 3;
}
message GetUserWorkMomentsCommentsMsgReq {
string userID = 1;
string operationID = 2;
server_api_params.RequestPagination Pagination = 3;
}
message GetUserWorkMomentsCommentsMsgResp {
CommonResp commonResp = 1;
repeated CommentsMsg commentsMsgs = 2;
server_api_params.ResponsePagination Pagination = 3;
}
message ClearUserWorkMomentsCommentsMsgReq {
string userID = 1;
string operationID = 2;
}
message ClearUserWorkMomentsCommentsMsgResp {
CommonResp commonResp = 1;
}
message SetUserWorkMomentsLevelReq {
string userID = 1;
int32 level = 2;
string operationID = 3;
}
message SetUserWorkMomentsLevelResp {
CommonResp commonResp = 1;
}
service OfficeService {
rpc GetUserTags(GetUserTagsReq) returns(GetUserTagsResp);
rpc CreateTag(CreateTagReq) returns(CreateTagResp);
rpc DeleteTag(DeleteTagReq) returns(DeleteTagResp);
rpc SetTag(SetTagReq) returns(SetTagResp);
rpc SendMsg2Tag(SendMsg2TagReq) returns(SendMsg2TagResp);
rpc GetTagSendLogs(GetTagSendLogsReq) returns(GetTagSendLogsResp);
rpc GetUserTagByID(GetUserTagByIDReq) returns(GetUserTagByIDResp);
rpc CreateOneWorkMoment(CreateOneWorkMomentReq) returns(CreateOneWorkMomentResp);
rpc DeleteOneWorkMoment(DeleteOneWorkMomentReq) returns(DeleteOneWorkMomentResp);
rpc LikeOneWorkMoment(LikeOneWorkMomentReq) returns(LikeOneWorkMomentResp);
rpc CommentOneWorkMoment(CommentOneWorkMomentReq) returns(CommentOneWorkMomentResp);
/// user self
rpc GetUserWorkMoments(GetUserWorkMomentsReq) returns(GetUserWorkMomentsResp);
/// users friend
rpc GetUserFriendWorkMoments(GetUserFriendWorkMomentsReq) returns(GetUserFriendWorkMomentsResp);
rpc GetUserWorkMomentsCommentsMsg(GetUserWorkMomentsCommentsMsgReq) returns(GetUserWorkMomentsCommentsMsgResp);
rpc ClearUserWorkMomentsCommentsMsg(ClearUserWorkMomentsCommentsMsgReq) returns(ClearUserWorkMomentsCommentsMsgResp);
rpc SetUserWorkMomentsLevel(SetUserWorkMomentsLevelReq) returns(SetUserWorkMomentsLevelResp);
}
File diff suppressed because it is too large Load Diff
+172
View File
@@ -0,0 +1,172 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./organization;organization";
package organization;
message CreateDepartmentReq{
server_api_params.Department departmentInfo = 1;
string operationID = 2;
string opUserID = 3;
}
message CreateDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
server_api_params.Department departmentInfo = 3;
}
message UpdateDepartmentReq{
server_api_params.Department departmentInfo = 1;
string operationID = 2;
string opUserID = 3;
}
message UpdateDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
}
message GetSubDepartmentReq{
string departmentID = 1;
string operationID = 2;
string opUserID = 3;
}
message GetSubDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
repeated server_api_params.Department departmentList = 3;
}
message DeleteDepartmentReq{
string departmentID = 1;
string operationID = 2;
string opUserID = 3;
}
message DeleteDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
}
message CreateOrganizationUserReq{
server_api_params.OrganizationUser organizationUser = 1;
string operationID = 2;
string opUserID = 3;
}
message CreateOrganizationUserResp{
int32 errCode = 1;
string errMsg = 2;
}
message UpdateOrganizationUserReq{
server_api_params.OrganizationUser organizationUser = 1;
string operationID = 2;
string opUserID = 3;
}
message UpdateOrganizationUserResp{
int32 errCode = 1;
string errMsg = 2;
}
message CreateDepartmentMemberReq{
server_api_params.UserInDepartment userInDepartment = 1;
string operationID = 2;
string opUserID = 3;
}
message CreateDepartmentMemberResp{
int32 errCode = 1;
string errMsg = 2;
}
message GetUserInDepartmentReq{
string userID = 1;
string operationID = 2;
string opUserID = 3;
}
message GetUserInDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
server_api_params.UserInDepartment userInDepartment = 3;
}
message UpdateUserInDepartmentReq{
server_api_params.DepartmentMember departmentMember = 1;
string operationID = 2;
string opUserID = 3;
}
message UpdateUserInDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
}
message DeleteUserInDepartmentReq{
string userID = 1;
string operationID = 2;
string opUserID = 3;
string departmentID = 4;
}
message DeleteUserInDepartmentResp{
int32 errCode = 1;
string errMsg = 2;
}
message DeleteOrganizationUserReq{
string userID = 1;
string operationID = 2;
string opUserID = 3;
}
message DeleteOrganizationUserResp{
int32 errCode = 1;
string errMsg = 2;
}
message GetDepartmentMemberReq{
string departmentID = 1;
string operationID = 2;
string opUserID = 3;
}
message GetDepartmentMemberResp{
int32 errCode = 1;
string errMsg = 2;
repeated server_api_params.UserInDepartment userInDepartmentList = 3;
}
service organization{
rpc CreateDepartment(CreateDepartmentReq) returns(CreateDepartmentResp);
rpc UpdateDepartment(UpdateDepartmentReq) returns(UpdateDepartmentResp);
rpc GetSubDepartment(GetSubDepartmentReq) returns(GetSubDepartmentResp);
rpc DeleteDepartment(DeleteDepartmentReq) returns(DeleteDepartmentResp);
rpc CreateOrganizationUser(CreateOrganizationUserReq) returns(CreateOrganizationUserResp);
rpc UpdateOrganizationUser(UpdateOrganizationUserReq) returns(UpdateOrganizationUserResp);
rpc DeleteOrganizationUser(DeleteOrganizationUserReq) returns(DeleteOrganizationUserResp);
rpc CreateDepartmentMember(CreateDepartmentMemberReq) returns(CreateDepartmentMemberResp);
rpc GetUserInDepartment(GetUserInDepartmentReq) returns(GetUserInDepartmentResp);
rpc DeleteUserInDepartment(DeleteUserInDepartmentReq) returns(DeleteUserInDepartmentResp);
rpc UpdateUserInDepartment(UpdateUserInDepartmentReq) returns(UpdateUserInDepartmentResp);
rpc GetDepartmentMember(GetDepartmentMemberReq) returns(GetDepartmentMemberResp);
}
+15
View File
@@ -0,0 +1,15 @@
all_proto=(
message_cms/message_cms.proto
admin_cms/admin_cms.proto
statistics/statistics.proto
auth/auth.proto
friend/friend.proto
group/group.proto
user/user.proto
rtc/rtc.proto
chat/chat.proto
push/push.proto
relay/relay.proto
sdk_ws/ws.proto
)
+216
View File
@@ -0,0 +1,216 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: push/push.proto
package pbPush // import "./push"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import sdk_ws "Open_IM/pkg/proto/sdk_ws"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type PushMsgReq struct {
OperationID string `protobuf:"bytes,1,opt,name=operationID" json:"operationID,omitempty"`
MsgData *sdk_ws.MsgData `protobuf:"bytes,2,opt,name=msgData" json:"msgData,omitempty"`
PushToUserID string `protobuf:"bytes,3,opt,name=pushToUserID" json:"pushToUserID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PushMsgReq) Reset() { *m = PushMsgReq{} }
func (m *PushMsgReq) String() string { return proto.CompactTextString(m) }
func (*PushMsgReq) ProtoMessage() {}
func (*PushMsgReq) Descriptor() ([]byte, []int) {
return fileDescriptor_push_76409d0b017416ef, []int{0}
}
func (m *PushMsgReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PushMsgReq.Unmarshal(m, b)
}
func (m *PushMsgReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PushMsgReq.Marshal(b, m, deterministic)
}
func (dst *PushMsgReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_PushMsgReq.Merge(dst, src)
}
func (m *PushMsgReq) XXX_Size() int {
return xxx_messageInfo_PushMsgReq.Size(m)
}
func (m *PushMsgReq) XXX_DiscardUnknown() {
xxx_messageInfo_PushMsgReq.DiscardUnknown(m)
}
var xxx_messageInfo_PushMsgReq proto.InternalMessageInfo
func (m *PushMsgReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *PushMsgReq) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
func (m *PushMsgReq) GetPushToUserID() string {
if m != nil {
return m.PushToUserID
}
return ""
}
type PushMsgResp struct {
ResultCode int32 `protobuf:"varint,1,opt,name=ResultCode" json:"ResultCode,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PushMsgResp) Reset() { *m = PushMsgResp{} }
func (m *PushMsgResp) String() string { return proto.CompactTextString(m) }
func (*PushMsgResp) ProtoMessage() {}
func (*PushMsgResp) Descriptor() ([]byte, []int) {
return fileDescriptor_push_76409d0b017416ef, []int{1}
}
func (m *PushMsgResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PushMsgResp.Unmarshal(m, b)
}
func (m *PushMsgResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PushMsgResp.Marshal(b, m, deterministic)
}
func (dst *PushMsgResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_PushMsgResp.Merge(dst, src)
}
func (m *PushMsgResp) XXX_Size() int {
return xxx_messageInfo_PushMsgResp.Size(m)
}
func (m *PushMsgResp) XXX_DiscardUnknown() {
xxx_messageInfo_PushMsgResp.DiscardUnknown(m)
}
var xxx_messageInfo_PushMsgResp proto.InternalMessageInfo
func (m *PushMsgResp) GetResultCode() int32 {
if m != nil {
return m.ResultCode
}
return 0
}
func init() {
proto.RegisterType((*PushMsgReq)(nil), "push.PushMsgReq")
proto.RegisterType((*PushMsgResp)(nil), "push.PushMsgResp")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// Client API for PushMsgService service
type PushMsgServiceClient interface {
PushMsg(ctx context.Context, in *PushMsgReq, opts ...grpc.CallOption) (*PushMsgResp, error)
}
type pushMsgServiceClient struct {
cc *grpc.ClientConn
}
func NewPushMsgServiceClient(cc *grpc.ClientConn) PushMsgServiceClient {
return &pushMsgServiceClient{cc}
}
func (c *pushMsgServiceClient) PushMsg(ctx context.Context, in *PushMsgReq, opts ...grpc.CallOption) (*PushMsgResp, error) {
out := new(PushMsgResp)
err := grpc.Invoke(ctx, "/push.PushMsgService/PushMsg", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for PushMsgService service
type PushMsgServiceServer interface {
PushMsg(context.Context, *PushMsgReq) (*PushMsgResp, error)
}
func RegisterPushMsgServiceServer(s *grpc.Server, srv PushMsgServiceServer) {
s.RegisterService(&_PushMsgService_serviceDesc, srv)
}
func _PushMsgService_PushMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PushMsgReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(PushMsgServiceServer).PushMsg(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/push.PushMsgService/PushMsg",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(PushMsgServiceServer).PushMsg(ctx, req.(*PushMsgReq))
}
return interceptor(ctx, in, info, handler)
}
var _PushMsgService_serviceDesc = grpc.ServiceDesc{
ServiceName: "push.PushMsgService",
HandlerType: (*PushMsgServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "PushMsg",
Handler: _PushMsgService_PushMsg_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "push/push.proto",
}
func init() { proto.RegisterFile("push/push.proto", fileDescriptor_push_76409d0b017416ef) }
var fileDescriptor_push_76409d0b017416ef = []byte{
// 249 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0x3d, 0x4f, 0xc3, 0x30,
0x10, 0x86, 0x15, 0xbe, 0x2a, 0x2e, 0x40, 0xc1, 0x53, 0x94, 0x01, 0x85, 0x4c, 0x5d, 0xb0, 0xa5,
0xc2, 0xc6, 0x82, 0x20, 0x4b, 0x86, 0x08, 0x64, 0x60, 0x61, 0x89, 0x5c, 0x7a, 0x4a, 0xa3, 0xd2,
0xfa, 0xf0, 0x25, 0xed, 0x5f, 0xe0, 0x67, 0xa3, 0xb8, 0x05, 0x02, 0x8b, 0x65, 0x3d, 0xf7, 0xe8,
0xf4, 0xde, 0x0b, 0x43, 0x6a, 0x79, 0xa6, 0xba, 0x47, 0x92, 0xb3, 0x8d, 0x15, 0x7b, 0xdd, 0x3f,
0xbe, 0x78, 0x20, 0x5c, 0x96, 0x79, 0xa1, 0x68, 0x5e, 0x29, 0x3f, 0x50, 0x3c, 0x9d, 0x97, 0x6b,
0x56, 0x6b, 0xde, 0x88, 0xe9, 0x67, 0x00, 0xf0, 0xd8, 0xf2, 0xac, 0xe0, 0x4a, 0xe3, 0x87, 0x48,
0x20, 0xb4, 0x84, 0xce, 0x34, 0xb5, 0x5d, 0xe6, 0x59, 0x14, 0x24, 0xc1, 0xe8, 0x50, 0xf7, 0x91,
0xb8, 0x86, 0xc1, 0x82, 0xab, 0xcc, 0x34, 0x26, 0xda, 0x49, 0x82, 0x51, 0x38, 0x8e, 0x25, 0xa3,
0x5b, 0xa1, 0x2b, 0x0d, 0xd5, 0x25, 0x19, 0x67, 0x16, 0x2c, 0x8b, 0x8d, 0xa1, 0xbf, 0x55, 0x91,
0xc2, 0x51, 0x97, 0xe8, 0xd9, 0xbe, 0x30, 0xba, 0x3c, 0x8b, 0x76, 0xfd, 0xe2, 0x3f, 0x2c, 0xbd,
0x84, 0xf0, 0x27, 0x09, 0x93, 0x38, 0x07, 0xd0, 0xc8, 0xed, 0x7b, 0x73, 0x6f, 0xa7, 0xe8, 0x93,
0xec, 0xeb, 0x1e, 0x19, 0xdf, 0xc2, 0xc9, 0x56, 0x7f, 0x42, 0xb7, 0xaa, 0xdf, 0x50, 0x48, 0x18,
0x6c, 0x89, 0x38, 0x95, 0xbe, 0x8c, 0xdf, 0xcb, 0xe2, 0xb3, 0x7f, 0x84, 0xe9, 0x6e, 0xf8, 0x7a,
0x2c, 0x7d, 0x69, 0x37, 0x34, 0xe9, 0xf8, 0xe4, 0xc0, 0x77, 0x72, 0xf5, 0x15, 0x00, 0x00, 0xff,
0xff, 0xbe, 0xb7, 0x7c, 0x1c, 0x4f, 0x01, 0x00, 0x00,
}
+38
View File
@@ -0,0 +1,38 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./push;pbPush";
package push;
message PushMsgReq {
string operationID = 1;
server_api_params.MsgData msgData = 2;
string pushToUserID = 3;
}
message PushMsgResp{
int32 ResultCode = 1;
}
//message InternalPushMsgReq{
// int32 ReqIdentifier = 1;
// string Token = 2;
// string SendID = 3;
// string OperationID = 4;
// int32 MsgIncr = 5;
// int32 PlatformID = 6;
// int32 SessionType = 7;
// int32 MsgFrom = 8;
// int32 ContentType = 9;
// string RecvID = 10;
// repeated string ForceList = 11;
// string Content = 12;
// string Options = 13;
// string ClientMsgID = 14;
// string OffLineInfo = 15;
// string Ex = 16;
//
//}
service PushMsgService {
rpc PushMsg(PushMsgReq) returns(PushMsgResp);
// rpc InternalPushMsg(InternalPushMsgReq)returns(PushMsgResp);
}
+602
View File
@@ -0,0 +1,602 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: relay/relay.proto
package pbRelay // import "./relay"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import sdk_ws "Open_IM/pkg/proto/sdk_ws"
import (
context "golang.org/x/net/context"
grpc "google.golang.org/grpc"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type OnlinePushMsgReq struct {
OperationID string `protobuf:"bytes,1,opt,name=OperationID" json:"OperationID,omitempty"`
MsgData *sdk_ws.MsgData `protobuf:"bytes,2,opt,name=msgData" json:"msgData,omitempty"`
PushToUserID string `protobuf:"bytes,3,opt,name=pushToUserID" json:"pushToUserID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *OnlinePushMsgReq) Reset() { *m = OnlinePushMsgReq{} }
func (m *OnlinePushMsgReq) String() string { return proto.CompactTextString(m) }
func (*OnlinePushMsgReq) ProtoMessage() {}
func (*OnlinePushMsgReq) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{0}
}
func (m *OnlinePushMsgReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OnlinePushMsgReq.Unmarshal(m, b)
}
func (m *OnlinePushMsgReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OnlinePushMsgReq.Marshal(b, m, deterministic)
}
func (dst *OnlinePushMsgReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_OnlinePushMsgReq.Merge(dst, src)
}
func (m *OnlinePushMsgReq) XXX_Size() int {
return xxx_messageInfo_OnlinePushMsgReq.Size(m)
}
func (m *OnlinePushMsgReq) XXX_DiscardUnknown() {
xxx_messageInfo_OnlinePushMsgReq.DiscardUnknown(m)
}
var xxx_messageInfo_OnlinePushMsgReq proto.InternalMessageInfo
func (m *OnlinePushMsgReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *OnlinePushMsgReq) GetMsgData() *sdk_ws.MsgData {
if m != nil {
return m.MsgData
}
return nil
}
func (m *OnlinePushMsgReq) GetPushToUserID() string {
if m != nil {
return m.PushToUserID
}
return ""
}
type OnlinePushMsgResp struct {
Resp []*SingleMsgToUser `protobuf:"bytes,1,rep,name=resp" json:"resp,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *OnlinePushMsgResp) Reset() { *m = OnlinePushMsgResp{} }
func (m *OnlinePushMsgResp) String() string { return proto.CompactTextString(m) }
func (*OnlinePushMsgResp) ProtoMessage() {}
func (*OnlinePushMsgResp) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{1}
}
func (m *OnlinePushMsgResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_OnlinePushMsgResp.Unmarshal(m, b)
}
func (m *OnlinePushMsgResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_OnlinePushMsgResp.Marshal(b, m, deterministic)
}
func (dst *OnlinePushMsgResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_OnlinePushMsgResp.Merge(dst, src)
}
func (m *OnlinePushMsgResp) XXX_Size() int {
return xxx_messageInfo_OnlinePushMsgResp.Size(m)
}
func (m *OnlinePushMsgResp) XXX_DiscardUnknown() {
xxx_messageInfo_OnlinePushMsgResp.DiscardUnknown(m)
}
var xxx_messageInfo_OnlinePushMsgResp proto.InternalMessageInfo
func (m *OnlinePushMsgResp) GetResp() []*SingleMsgToUser {
if m != nil {
return m.Resp
}
return nil
}
type SingleMsgToUser struct {
ResultCode int64 `protobuf:"varint,1,opt,name=ResultCode" json:"ResultCode,omitempty"`
RecvID string `protobuf:"bytes,2,opt,name=RecvID" json:"RecvID,omitempty"`
RecvPlatFormID int32 `protobuf:"varint,3,opt,name=RecvPlatFormID" json:"RecvPlatFormID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *SingleMsgToUser) Reset() { *m = SingleMsgToUser{} }
func (m *SingleMsgToUser) String() string { return proto.CompactTextString(m) }
func (*SingleMsgToUser) ProtoMessage() {}
func (*SingleMsgToUser) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{2}
}
func (m *SingleMsgToUser) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_SingleMsgToUser.Unmarshal(m, b)
}
func (m *SingleMsgToUser) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_SingleMsgToUser.Marshal(b, m, deterministic)
}
func (dst *SingleMsgToUser) XXX_Merge(src proto.Message) {
xxx_messageInfo_SingleMsgToUser.Merge(dst, src)
}
func (m *SingleMsgToUser) XXX_Size() int {
return xxx_messageInfo_SingleMsgToUser.Size(m)
}
func (m *SingleMsgToUser) XXX_DiscardUnknown() {
xxx_messageInfo_SingleMsgToUser.DiscardUnknown(m)
}
var xxx_messageInfo_SingleMsgToUser proto.InternalMessageInfo
func (m *SingleMsgToUser) GetResultCode() int64 {
if m != nil {
return m.ResultCode
}
return 0
}
func (m *SingleMsgToUser) GetRecvID() string {
if m != nil {
return m.RecvID
}
return ""
}
func (m *SingleMsgToUser) GetRecvPlatFormID() int32 {
if m != nil {
return m.RecvPlatFormID
}
return 0
}
type GetUsersOnlineStatusReq struct {
UserIDList []string `protobuf:"bytes,1,rep,name=userIDList" json:"userIDList,omitempty"`
OperationID string `protobuf:"bytes,2,opt,name=operationID" json:"operationID,omitempty"`
OpUserID string `protobuf:"bytes,3,opt,name=opUserID" json:"opUserID,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetUsersOnlineStatusReq) Reset() { *m = GetUsersOnlineStatusReq{} }
func (m *GetUsersOnlineStatusReq) String() string { return proto.CompactTextString(m) }
func (*GetUsersOnlineStatusReq) ProtoMessage() {}
func (*GetUsersOnlineStatusReq) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{3}
}
func (m *GetUsersOnlineStatusReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetUsersOnlineStatusReq.Unmarshal(m, b)
}
func (m *GetUsersOnlineStatusReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetUsersOnlineStatusReq.Marshal(b, m, deterministic)
}
func (dst *GetUsersOnlineStatusReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetUsersOnlineStatusReq.Merge(dst, src)
}
func (m *GetUsersOnlineStatusReq) XXX_Size() int {
return xxx_messageInfo_GetUsersOnlineStatusReq.Size(m)
}
func (m *GetUsersOnlineStatusReq) XXX_DiscardUnknown() {
xxx_messageInfo_GetUsersOnlineStatusReq.DiscardUnknown(m)
}
var xxx_messageInfo_GetUsersOnlineStatusReq proto.InternalMessageInfo
func (m *GetUsersOnlineStatusReq) GetUserIDList() []string {
if m != nil {
return m.UserIDList
}
return nil
}
func (m *GetUsersOnlineStatusReq) GetOperationID() string {
if m != nil {
return m.OperationID
}
return ""
}
func (m *GetUsersOnlineStatusReq) GetOpUserID() string {
if m != nil {
return m.OpUserID
}
return ""
}
type GetUsersOnlineStatusResp struct {
ErrCode int32 `protobuf:"varint,1,opt,name=errCode" json:"errCode,omitempty"`
ErrMsg string `protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"`
SuccessResult []*GetUsersOnlineStatusResp_SuccessResult `protobuf:"bytes,3,rep,name=successResult" json:"successResult,omitempty"`
FailedResult []*GetUsersOnlineStatusResp_FailedDetail `protobuf:"bytes,4,rep,name=failedResult" json:"failedResult,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetUsersOnlineStatusResp) Reset() { *m = GetUsersOnlineStatusResp{} }
func (m *GetUsersOnlineStatusResp) String() string { return proto.CompactTextString(m) }
func (*GetUsersOnlineStatusResp) ProtoMessage() {}
func (*GetUsersOnlineStatusResp) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{4}
}
func (m *GetUsersOnlineStatusResp) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetUsersOnlineStatusResp.Unmarshal(m, b)
}
func (m *GetUsersOnlineStatusResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetUsersOnlineStatusResp.Marshal(b, m, deterministic)
}
func (dst *GetUsersOnlineStatusResp) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetUsersOnlineStatusResp.Merge(dst, src)
}
func (m *GetUsersOnlineStatusResp) XXX_Size() int {
return xxx_messageInfo_GetUsersOnlineStatusResp.Size(m)
}
func (m *GetUsersOnlineStatusResp) XXX_DiscardUnknown() {
xxx_messageInfo_GetUsersOnlineStatusResp.DiscardUnknown(m)
}
var xxx_messageInfo_GetUsersOnlineStatusResp proto.InternalMessageInfo
func (m *GetUsersOnlineStatusResp) GetErrCode() int32 {
if m != nil {
return m.ErrCode
}
return 0
}
func (m *GetUsersOnlineStatusResp) GetErrMsg() string {
if m != nil {
return m.ErrMsg
}
return ""
}
func (m *GetUsersOnlineStatusResp) GetSuccessResult() []*GetUsersOnlineStatusResp_SuccessResult {
if m != nil {
return m.SuccessResult
}
return nil
}
func (m *GetUsersOnlineStatusResp) GetFailedResult() []*GetUsersOnlineStatusResp_FailedDetail {
if m != nil {
return m.FailedResult
}
return nil
}
type GetUsersOnlineStatusResp_SuccessDetail struct {
Platform string `protobuf:"bytes,1,opt,name=platform" json:"platform,omitempty"`
Status string `protobuf:"bytes,2,opt,name=status" json:"status,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) Reset() {
*m = GetUsersOnlineStatusResp_SuccessDetail{}
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) String() string { return proto.CompactTextString(m) }
func (*GetUsersOnlineStatusResp_SuccessDetail) ProtoMessage() {}
func (*GetUsersOnlineStatusResp_SuccessDetail) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{4, 0}
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail.Unmarshal(m, b)
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail.Marshal(b, m, deterministic)
}
func (dst *GetUsersOnlineStatusResp_SuccessDetail) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail.Merge(dst, src)
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) XXX_Size() int {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail.Size(m)
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) XXX_DiscardUnknown() {
xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail.DiscardUnknown(m)
}
var xxx_messageInfo_GetUsersOnlineStatusResp_SuccessDetail proto.InternalMessageInfo
func (m *GetUsersOnlineStatusResp_SuccessDetail) GetPlatform() string {
if m != nil {
return m.Platform
}
return ""
}
func (m *GetUsersOnlineStatusResp_SuccessDetail) GetStatus() string {
if m != nil {
return m.Status
}
return ""
}
type GetUsersOnlineStatusResp_FailedDetail struct {
UserID string `protobuf:"bytes,3,opt,name=userID" json:"userID,omitempty"`
ErrCode int32 `protobuf:"varint,1,opt,name=errCode" json:"errCode,omitempty"`
ErrMsg string `protobuf:"bytes,2,opt,name=errMsg" json:"errMsg,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetUsersOnlineStatusResp_FailedDetail) Reset() { *m = GetUsersOnlineStatusResp_FailedDetail{} }
func (m *GetUsersOnlineStatusResp_FailedDetail) String() string { return proto.CompactTextString(m) }
func (*GetUsersOnlineStatusResp_FailedDetail) ProtoMessage() {}
func (*GetUsersOnlineStatusResp_FailedDetail) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{4, 1}
}
func (m *GetUsersOnlineStatusResp_FailedDetail) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail.Unmarshal(m, b)
}
func (m *GetUsersOnlineStatusResp_FailedDetail) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail.Marshal(b, m, deterministic)
}
func (dst *GetUsersOnlineStatusResp_FailedDetail) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail.Merge(dst, src)
}
func (m *GetUsersOnlineStatusResp_FailedDetail) XXX_Size() int {
return xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail.Size(m)
}
func (m *GetUsersOnlineStatusResp_FailedDetail) XXX_DiscardUnknown() {
xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail.DiscardUnknown(m)
}
var xxx_messageInfo_GetUsersOnlineStatusResp_FailedDetail proto.InternalMessageInfo
func (m *GetUsersOnlineStatusResp_FailedDetail) GetUserID() string {
if m != nil {
return m.UserID
}
return ""
}
func (m *GetUsersOnlineStatusResp_FailedDetail) GetErrCode() int32 {
if m != nil {
return m.ErrCode
}
return 0
}
func (m *GetUsersOnlineStatusResp_FailedDetail) GetErrMsg() string {
if m != nil {
return m.ErrMsg
}
return ""
}
type GetUsersOnlineStatusResp_SuccessResult struct {
UserID string `protobuf:"bytes,1,opt,name=userID" json:"userID,omitempty"`
Status string `protobuf:"bytes,2,opt,name=status" json:"status,omitempty"`
DetailPlatformStatus []*GetUsersOnlineStatusResp_SuccessDetail `protobuf:"bytes,3,rep,name=detailPlatformStatus" json:"detailPlatformStatus,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *GetUsersOnlineStatusResp_SuccessResult) Reset() {
*m = GetUsersOnlineStatusResp_SuccessResult{}
}
func (m *GetUsersOnlineStatusResp_SuccessResult) String() string { return proto.CompactTextString(m) }
func (*GetUsersOnlineStatusResp_SuccessResult) ProtoMessage() {}
func (*GetUsersOnlineStatusResp_SuccessResult) Descriptor() ([]byte, []int) {
return fileDescriptor_relay_34094e5333f6005a, []int{4, 2}
}
func (m *GetUsersOnlineStatusResp_SuccessResult) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult.Unmarshal(m, b)
}
func (m *GetUsersOnlineStatusResp_SuccessResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult.Marshal(b, m, deterministic)
}
func (dst *GetUsersOnlineStatusResp_SuccessResult) XXX_Merge(src proto.Message) {
xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult.Merge(dst, src)
}
func (m *GetUsersOnlineStatusResp_SuccessResult) XXX_Size() int {
return xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult.Size(m)
}
func (m *GetUsersOnlineStatusResp_SuccessResult) XXX_DiscardUnknown() {
xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult.DiscardUnknown(m)
}
var xxx_messageInfo_GetUsersOnlineStatusResp_SuccessResult proto.InternalMessageInfo
func (m *GetUsersOnlineStatusResp_SuccessResult) GetUserID() string {
if m != nil {
return m.UserID
}
return ""
}
func (m *GetUsersOnlineStatusResp_SuccessResult) GetStatus() string {
if m != nil {
return m.Status
}
return ""
}
func (m *GetUsersOnlineStatusResp_SuccessResult) GetDetailPlatformStatus() []*GetUsersOnlineStatusResp_SuccessDetail {
if m != nil {
return m.DetailPlatformStatus
}
return nil
}
func init() {
proto.RegisterType((*OnlinePushMsgReq)(nil), "relay.OnlinePushMsgReq")
proto.RegisterType((*OnlinePushMsgResp)(nil), "relay.OnlinePushMsgResp")
proto.RegisterType((*SingleMsgToUser)(nil), "relay.SingleMsgToUser")
proto.RegisterType((*GetUsersOnlineStatusReq)(nil), "relay.GetUsersOnlineStatusReq")
proto.RegisterType((*GetUsersOnlineStatusResp)(nil), "relay.GetUsersOnlineStatusResp")
proto.RegisterType((*GetUsersOnlineStatusResp_SuccessDetail)(nil), "relay.GetUsersOnlineStatusResp.SuccessDetail")
proto.RegisterType((*GetUsersOnlineStatusResp_FailedDetail)(nil), "relay.GetUsersOnlineStatusResp.FailedDetail")
proto.RegisterType((*GetUsersOnlineStatusResp_SuccessResult)(nil), "relay.GetUsersOnlineStatusResp.SuccessResult")
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// 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.SupportPackageIsVersion4
// Client API for OnlineMessageRelayService service
type OnlineMessageRelayServiceClient interface {
OnlinePushMsg(ctx context.Context, in *OnlinePushMsgReq, opts ...grpc.CallOption) (*OnlinePushMsgResp, error)
GetUsersOnlineStatus(ctx context.Context, in *GetUsersOnlineStatusReq, opts ...grpc.CallOption) (*GetUsersOnlineStatusResp, error)
}
type onlineMessageRelayServiceClient struct {
cc *grpc.ClientConn
}
func NewOnlineMessageRelayServiceClient(cc *grpc.ClientConn) OnlineMessageRelayServiceClient {
return &onlineMessageRelayServiceClient{cc}
}
func (c *onlineMessageRelayServiceClient) OnlinePushMsg(ctx context.Context, in *OnlinePushMsgReq, opts ...grpc.CallOption) (*OnlinePushMsgResp, error) {
out := new(OnlinePushMsgResp)
err := grpc.Invoke(ctx, "/relay.OnlineMessageRelayService/OnlinePushMsg", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *onlineMessageRelayServiceClient) GetUsersOnlineStatus(ctx context.Context, in *GetUsersOnlineStatusReq, opts ...grpc.CallOption) (*GetUsersOnlineStatusResp, error) {
out := new(GetUsersOnlineStatusResp)
err := grpc.Invoke(ctx, "/relay.OnlineMessageRelayService/GetUsersOnlineStatus", in, out, c.cc, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// Server API for OnlineMessageRelayService service
type OnlineMessageRelayServiceServer interface {
OnlinePushMsg(context.Context, *OnlinePushMsgReq) (*OnlinePushMsgResp, error)
GetUsersOnlineStatus(context.Context, *GetUsersOnlineStatusReq) (*GetUsersOnlineStatusResp, error)
}
func RegisterOnlineMessageRelayServiceServer(s *grpc.Server, srv OnlineMessageRelayServiceServer) {
s.RegisterService(&_OnlineMessageRelayService_serviceDesc, srv)
}
func _OnlineMessageRelayService_OnlinePushMsg_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(OnlinePushMsgReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(OnlineMessageRelayServiceServer).OnlinePushMsg(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/relay.OnlineMessageRelayService/OnlinePushMsg",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(OnlineMessageRelayServiceServer).OnlinePushMsg(ctx, req.(*OnlinePushMsgReq))
}
return interceptor(ctx, in, info, handler)
}
func _OnlineMessageRelayService_GetUsersOnlineStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUsersOnlineStatusReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(OnlineMessageRelayServiceServer).GetUsersOnlineStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/relay.OnlineMessageRelayService/GetUsersOnlineStatus",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(OnlineMessageRelayServiceServer).GetUsersOnlineStatus(ctx, req.(*GetUsersOnlineStatusReq))
}
return interceptor(ctx, in, info, handler)
}
var _OnlineMessageRelayService_serviceDesc = grpc.ServiceDesc{
ServiceName: "relay.OnlineMessageRelayService",
HandlerType: (*OnlineMessageRelayServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "OnlinePushMsg",
Handler: _OnlineMessageRelayService_OnlinePushMsg_Handler,
},
{
MethodName: "GetUsersOnlineStatus",
Handler: _OnlineMessageRelayService_GetUsersOnlineStatus_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "relay/relay.proto",
}
func init() { proto.RegisterFile("relay/relay.proto", fileDescriptor_relay_34094e5333f6005a) }
var fileDescriptor_relay_34094e5333f6005a = []byte{
// 554 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x54, 0x5d, 0x8f, 0xd2, 0x40,
0x14, 0x4d, 0x65, 0x3f, 0xdc, 0x0b, 0xb8, 0x32, 0xd9, 0xec, 0xd6, 0x3e, 0x20, 0xf6, 0xc1, 0x10,
0xa3, 0x25, 0x41, 0xdf, 0x7c, 0x30, 0xd9, 0x25, 0x6b, 0x48, 0x6c, 0x20, 0x83, 0x46, 0xe3, 0x0b,
0x99, 0x85, 0xbb, 0xdd, 0x66, 0x0b, 0x1d, 0xe6, 0xb6, 0x10, 0xff, 0x84, 0x3f, 0xc2, 0x3f, 0xa1,
0x3f, 0xcf, 0x74, 0xa6, 0x60, 0x4b, 0x58, 0x37, 0xfb, 0x42, 0x38, 0x77, 0xee, 0x3d, 0xf7, 0x9c,
0xd3, 0x76, 0xa0, 0xa1, 0x30, 0x12, 0x3f, 0x3a, 0xfa, 0xd7, 0x93, 0x2a, 0x4e, 0x62, 0xb6, 0xaf,
0x81, 0xf3, 0x62, 0x20, 0x71, 0x3e, 0xee, 0xfb, 0x1d, 0x79, 0x1b, 0x74, 0xf4, 0x49, 0x87, 0xa6,
0xb7, 0xe3, 0x15, 0x75, 0x56, 0x64, 0x3a, 0xdd, 0x9f, 0x16, 0x3c, 0x1d, 0xcc, 0xa3, 0x70, 0x8e,
0xc3, 0x94, 0x6e, 0x7c, 0x0a, 0x38, 0x2e, 0x58, 0x0b, 0xaa, 0x03, 0x89, 0x4a, 0x24, 0x61, 0x3c,
0xef, 0xf7, 0x6c, 0xab, 0x65, 0xb5, 0x8f, 0x78, 0xb1, 0xc4, 0xde, 0xc1, 0xe1, 0x8c, 0x82, 0x9e,
0x48, 0x84, 0xfd, 0xa8, 0x65, 0xb5, 0xab, 0x5d, 0xc7, 0x23, 0x54, 0x4b, 0x54, 0x63, 0x21, 0xc3,
0xb1, 0x14, 0x4a, 0xcc, 0xc8, 0xf3, 0x4d, 0x07, 0x5f, 0xb7, 0x32, 0x17, 0x6a, 0x32, 0xa5, 0x9b,
0xcf, 0xf1, 0x17, 0x42, 0xd5, 0xef, 0xd9, 0x15, 0x4d, 0x5c, 0xaa, 0xb9, 0x1f, 0xa0, 0xb1, 0xa5,
0x87, 0x24, 0x7b, 0x05, 0x7b, 0x0a, 0x49, 0xda, 0x56, 0xab, 0xd2, 0xae, 0x76, 0x4f, 0x3d, 0xe3,
0x75, 0x14, 0xce, 0x83, 0x08, 0x7d, 0x0a, 0xcc, 0x30, 0xd7, 0x3d, 0xee, 0x02, 0x8e, 0xb7, 0x0e,
0x58, 0x13, 0x80, 0x23, 0xa5, 0x51, 0x72, 0x11, 0x4f, 0x51, 0xdb, 0xa9, 0xf0, 0x42, 0x85, 0x9d,
0xc2, 0x01, 0xc7, 0xc9, 0xb2, 0xdf, 0xd3, 0x66, 0x8e, 0x78, 0x8e, 0xd8, 0x4b, 0x78, 0x92, 0xfd,
0x1b, 0x46, 0x22, 0xb9, 0x8c, 0xd5, 0x2c, 0x57, 0xbc, 0xcf, 0xb7, 0xaa, 0xee, 0x0a, 0xce, 0x3e,
0x62, 0x92, 0xad, 0x22, 0xa3, 0x7d, 0x94, 0x88, 0x24, 0xa5, 0x2c, 0xca, 0x26, 0x40, 0xaa, 0x8d,
0x7d, 0x0a, 0x29, 0xd1, 0xfa, 0x8f, 0x78, 0xa1, 0x92, 0x45, 0x1d, 0x17, 0xa2, 0x36, 0xfb, 0x8b,
0x25, 0xe6, 0xc0, 0xe3, 0x58, 0x96, 0x02, 0xdb, 0x60, 0xf7, 0xf7, 0x1e, 0xd8, 0xbb, 0x37, 0x93,
0x64, 0x36, 0x1c, 0xa2, 0x52, 0x1b, 0xcb, 0xfb, 0x7c, 0x0d, 0x33, 0xbf, 0xa8, 0x94, 0x4f, 0xc1,
0xda, 0xaf, 0x41, 0x6c, 0x04, 0x75, 0x4a, 0x27, 0x13, 0x24, 0x32, 0xe1, 0xd8, 0x15, 0x9d, 0xf7,
0x9b, 0x3c, 0xef, 0xbb, 0x36, 0x79, 0xa3, 0xe2, 0x10, 0x2f, 0x73, 0xb0, 0x21, 0xd4, 0xae, 0x45,
0x18, 0xe1, 0x34, 0xe7, 0xdc, 0xd3, 0x9c, 0xaf, 0xef, 0xe3, 0xbc, 0xd4, 0x33, 0x3d, 0x4c, 0x44,
0x18, 0xf1, 0x12, 0x83, 0x73, 0x01, 0xf5, 0x7c, 0xa3, 0x39, 0xce, 0x22, 0x92, 0x91, 0x48, 0xae,
0x63, 0x35, 0xcb, 0x5f, 0xd6, 0x0d, 0xce, 0xbc, 0x92, 0x66, 0x5d, 0x7b, 0x35, 0xc8, 0xf9, 0x06,
0xb5, 0xe2, 0x8a, 0xac, 0x2f, 0x2d, 0x86, 0x9c, 0xa3, 0x87, 0xa7, 0xe8, 0xfc, 0xb2, 0x36, 0xfa,
0xf2, 0x08, 0xfe, 0x71, 0x5b, 0x25, 0xee, 0x3b, 0xb4, 0x31, 0x01, 0x27, 0x53, 0xad, 0x6a, 0x98,
0xbb, 0x30, 0xb9, 0x3c, 0xf0, 0x71, 0xe4, 0xd9, 0xed, 0xa4, 0xea, 0xfe, 0xb1, 0xe0, 0x99, 0x19,
0xf4, 0x91, 0x48, 0x04, 0xc8, 0x33, 0xce, 0x11, 0xaa, 0x65, 0x38, 0x41, 0x76, 0x0e, 0xf5, 0xd2,
0x47, 0xc8, 0xce, 0xf2, 0x9d, 0xdb, 0x57, 0x85, 0x63, 0xef, 0x3e, 0x20, 0xc9, 0xbe, 0xc2, 0xc9,
0x2e, 0x85, 0xac, 0xf9, 0x5f, 0xf9, 0x0b, 0xe7, 0xf9, 0x3d, 0xf6, 0xce, 0x1b, 0xdf, 0x8f, 0x3d,
0x73, 0xdb, 0xbd, 0x97, 0x57, 0x5a, 0xf6, 0xd5, 0x81, 0xbe, 0xcc, 0xde, 0xfe, 0x0d, 0x00, 0x00,
0xff, 0xff, 0x8e, 0xdc, 0xcc, 0x70, 0x0b, 0x05, 0x00, 0x00,
}
+61
View File
@@ -0,0 +1,61 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./relay;pbRelay";
package relay;
message OnlinePushMsgReq {
string OperationID = 1;
server_api_params.MsgData msgData = 2;
string pushToUserID = 3;
}
message OnlinePushMsgResp{
repeated SingleMsgToUser resp = 1;
}//message SendMsgByWSReq{
// string SendID = 1;
// string RecvID = 2;
// string Content = 3;
// int64 SendTime = 4;
// int64 MsgFrom = 5;
// int64 ContentType = 6;
// int64 SessionType = 7;
// string OperationID = 8;
// int64 PlatformID = 9;
//}
message SingleMsgToUser{
int64 ResultCode = 1;
string RecvID = 2;
int32 RecvPlatFormID = 3;
}
message GetUsersOnlineStatusReq{
repeated string userIDList = 1;
string operationID = 2;
string opUserID = 3;
}
message GetUsersOnlineStatusResp{
int32 errCode = 1;
string errMsg = 2;
repeated SuccessResult successResult = 3;
repeated FailedDetail failedResult = 4;
message SuccessDetail{
string platform = 1;
string status = 2;
}
message FailedDetail{
string userID = 3;
int32 errCode = 1;
string errMsg = 2;
}
message SuccessResult{
string userID = 1;
string status = 2;
repeated SuccessDetail detailPlatformStatus = 3;
}
}
service OnlineMessageRelayService {
rpc OnlinePushMsg(OnlinePushMsgReq) returns(OnlinePushMsgResp);
rpc GetUsersOnlineStatus(GetUsersOnlineStatusReq)returns(GetUsersOnlineStatusResp);
// rpc SendMsgByWS(SendMsgByWSReq) returns(MsgToUserResp);
}
File diff suppressed because it is too large Load Diff
+219
View File
@@ -0,0 +1,219 @@
syntax = "proto3";
option go_package = "./rtc;rtc";
package proto;
message CommonResp{
int32 errCode = 1;
string errMsg = 2;
}
message MsgData {
string sendID = 1;
string recvID = 2;
string groupID = 3;
string clientMsgID = 4;
string serverMsgID = 5;
int32 senderPlatformID = 6;
string senderNickname = 7;
string senderFaceURL = 8;
int32 sessionType = 9;
int32 msgFrom = 10;
int32 contentType = 11;
bytes content = 12;
uint32 seq = 14;
int64 sendTime = 15;
int64 createTime = 16;
int32 status = 17;
map<string, bool> options = 18;
OfflinePushInfo offlinePushInfo = 19;
}
message GroupInfo{
string groupID = 1;
string groupName = 2;
string notification = 3;
string introduction = 4;
string faceURL = 5;
string ownerUserID = 6;
uint32 createTime = 7;
uint32 memberCount = 8;
string ex = 9;
int32 status = 10;
string creatorUserID = 11;
int32 groupType = 12;
}
message GroupMemberFullInfo {
string groupID = 1 ;
string userID = 2 ;
int32 roleLevel = 3;
int32 joinTime = 4;
string nickname = 5;
string faceURL = 6;
int32 appMangerLevel = 7; //if >0
int32 joinSource = 8;
string operatorUserID = 9;
string ex = 10;
}
message ParticipantMetaData{
GroupInfo groupInfo = 1;
GroupMemberFullInfo groupMemberInfo = 2;
PublicUserInfo userInfo = 3;
}
message PublicUserInfo{
string userID = 1;
string nickname = 2;
string faceURL = 3;
int32 gender = 4;
string ex = 5;
}
message GetJoinTokenReq{
string room = 1;
string identity = 2;
ParticipantMetaData metaData = 3;
string operationID = 4;
}
message GetJoinTokenResp{
CommonResp CommonResp = 1;
string jwt = 2;
string liveURL = 3;
}
message OfflinePushInfo{
string title = 1;
string desc = 2;
string ex = 3;
string iOSPushSound = 4;
bool iOSBadgeCount = 5;
}
message SignalReq {
oneof payload {
SignalInviteReq invite = 1;
SignalInviteInGroupReq inviteInGroup= 2;
SignalCancelReq cancel = 3;
SignalAcceptReq accept = 4;
SignalHungUpReq hungUp = 5;
SignalRejectReq reject = 6;
}
}
message SignalResp {
oneof payload {
SignalInviteReply invite = 1;
SignalInviteInGroupReply inviteInGroup= 2;
SignalCancelReply cancel = 3;
SignalAcceptReply accept = 4;
SignalHungUpReply hungUp = 5;
SignalRejectReply reject = 6;
}
}
message InvitationInfo {
string inviterUserID = 1;
repeated string inviteeUserIDList = 2;
string customData = 3;
string groupID = 4;
string roomID = 5;
int32 timeout = 6;
string mediaType = 7;
int32 platformID = 8;
int32 sessionType = 9;
}
message SignalInviteReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalInviteReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalInviteInGroupReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalInviteInGroupReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalCancelReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalCancelReply {
}
message SignalAcceptReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
int32 opUserPlatformID = 5;
}
message SignalAcceptReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalHungUpReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
}
message SignalHungUpReply {
}
message SignalRejectReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
int32 opUserPlatformID = 5;
}
message SignalRejectReply {
}
message SignalMessageAssembleReq {
SignalReq signalReq = 1;
string operationID = 2;
}
message SignalMessageAssembleResp {
CommonResp commonResp = 1;
bool isPass = 2;
SignalResp signalResp = 3;
MsgData msgData = 4;
}
service RtcService {
rpc SignalMessageAssemble(SignalMessageAssembleReq) returns(SignalMessageAssembleResp);
}
File diff suppressed because it is too large Load Diff
+571
View File
@@ -0,0 +1,571 @@
syntax = "proto3";
option go_package = "./sdk_ws;server_api_params";
package server_api_params;
////////////////////////////////base///////////////////////////////
message GroupInfo{
string groupID = 1;
string groupName = 2;
string notification = 3;
string introduction = 4;
string faceURL = 5;
string ownerUserID = 6;
uint32 createTime = 7;
uint32 memberCount = 8;
string ex = 9;
int32 status = 10;
string creatorUserID = 11;
int32 groupType = 12;
}
message GroupMemberFullInfo {
string groupID = 1 ;
string userID = 2 ;
int32 roleLevel = 3;
int32 joinTime = 4;
string nickname = 5;
string faceURL = 6;
int32 appMangerLevel = 7; //if >0
int32 joinSource = 8;
string operatorUserID = 9;
string ex = 10;
uint32 muteEndTime = 11;
}
message PublicUserInfo{
string userID = 1;
string nickname = 2;
string faceURL = 3;
int32 gender = 4;
string ex = 5;
}
message UserInfo{
string userID = 1;
string nickname = 2;
string faceURL = 3;
int32 gender = 4;
string phoneNumber = 5;
uint32 birth = 6;
string email = 7;
string ex = 8;
uint32 createTime = 9;
int32 appMangerLevel = 10;
}
message FriendInfo{
string ownerUserID = 1;
string remark = 2;
uint32 createTime = 3;
UserInfo friendUser = 4;
int32 addSource = 5;
string operatorUserID = 6;
string ex = 7;
}
message BlackInfo{
string ownerUserID = 1;
uint32 createTime = 2;
PublicUserInfo blackUserInfo = 3;
int32 addSource = 4;
string operatorUserID = 5;
string ex = 6;
}
message GroupRequest{
PublicUserInfo userInfo = 1;
GroupInfo groupInfo = 2;
int32 handleResult = 3;
string reqMsg = 4;
string handleMsg = 5;
uint32 reqTime = 6;
string handleUserID = 7;
uint32 handleTime = 8;
string ex = 9;
}
message FriendRequest{
string fromUserID = 1;
string fromNickname = 2;
string fromFaceURL = 3;
int32 fromGender = 4;
string toUserID = 5;
string toNickname = 6;
string toFaceURL = 7;
int32 toGender = 8;
int32 handleResult = 9;
string reqMsg = 10;
uint32 createTime = 11;
string handlerUserID = 12;
string handleMsg = 13;
uint32 handleTime = 14;
string ex = 15;
}
///////////////////////////////////organization/////////////////////////////////////
message Department {
string departmentID = 1;
string faceURL = 2;
string name = 3;
string parentID = 4;
int32 order = 5;
int32 departmentType = 6;
uint32 createTime = 7;
uint32 subDepartmentNum = 8;
uint32 memberNum = 9;
string ex = 10;
}
message OrganizationUser {
string userID = 1;
string nickname = 2;
string englishName = 3;
string faceURL = 4;
int32 gender = 5;
string mobile = 6;
string telephone = 7;
uint32 birth = 8;
string email = 9;
uint32 createTime = 10;
string ex = 11;
}
message DepartmentMember {
string userID = 1;
string DepartmentID = 2;
int32 Order = 3;
string Position = 4;
int32 Leader = 5;
int32 Status = 6;
string Ex = 7;
}
message UserInDepartment {
OrganizationUser organizationUser = 1;
repeated DepartmentMember departmentMemberList = 2;
}
///////////////////////////////////organization end//////////////////////////////////
///////////////////////////////////base end/////////////////////////////////////
message PullMessageBySeqListResp {
int32 errCode = 1;
string errMsg = 2;
repeated MsgData list = 3;
}
message PullMessageBySeqListReq{
string userID = 1;
string operationID = 2;
repeated uint32 seqList = 3;
}
message GetMaxAndMinSeqReq {
}
message GetMaxAndMinSeqResp {
uint32 maxSeq = 1;
uint32 minSeq = 2;
}
message UserSendMsgResp {
string serverMsgID = 1;
string clientMsgID = 2;
int64 sendTime = 3;
}
message MsgData {
string sendID = 1;
string recvID = 2;
string groupID = 3;
string clientMsgID = 4;
string serverMsgID = 5;
int32 senderPlatformID = 6;
string senderNickname = 7;
string senderFaceURL = 8;
int32 sessionType = 9;
int32 msgFrom = 10;
int32 contentType = 11;
bytes content = 12;
uint32 seq = 14;
int64 sendTime = 15;
int64 createTime = 16;
int32 status = 17;
map<string, bool> options = 18;
OfflinePushInfo offlinePushInfo = 19;
}
message OfflinePushInfo{
string title = 1;
string desc = 2;
string ex = 3;
string iOSPushSound = 4;
bool iOSBadgeCount = 5;
}
message TipsComm{
bytes detail = 1;
string defaultTips = 2;
string jsonDetail = 3;
}
//////////////////////group/////////////////////
// OnGroupCreated()
message GroupCreatedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
repeated GroupMemberFullInfo memberList = 3;
int64 operationTime = 4;
GroupMemberFullInfo groupOwnerUser = 5;
}
// OnGroupInfoSet()
message GroupInfoSetTips{
GroupMemberFullInfo opUser = 1; //who do this
int64 muteTime = 2;
GroupInfo group = 3;
}
// OnJoinGroupApplication()
message JoinGroupApplicationTips{
GroupInfo group = 1;
PublicUserInfo applicant = 2;
string reqMsg = 3;
}
// OnQuitGroup()
//Actively leave the group
message MemberQuitTips{
GroupInfo group = 1;
GroupMemberFullInfo quitUser = 2;
int64 operationTime = 3;
}
// OnApplicationGroupAccepted()
message GroupApplicationAcceptedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
string handleMsg = 4;
}
// OnApplicationGroupRejected()
message GroupApplicationRejectedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
string handleMsg = 4;
}
// OnTransferGroupOwner()
message GroupOwnerTransferredTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
GroupMemberFullInfo newGroupOwner = 3;
int64 operationTime = 4;
}
// OnMemberKicked()
message MemberKickedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
repeated GroupMemberFullInfo kickedUserList = 3;
int64 operationTime = 4;
}
// OnMemberInvited()
message MemberInvitedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
repeated GroupMemberFullInfo invitedUserList = 3;
int64 operationTime = 4;
}
//Actively join the group
message MemberEnterTips{
GroupInfo group = 1;
GroupMemberFullInfo entrantUser = 2;
int64 operationTime = 3;
}
message GroupDismissedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
int64 operationTime = 3;
}
message GroupMemberMutedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
int64 operationTime = 3;
GroupMemberFullInfo mutedUser = 4;
uint32 mutedSeconds = 5;
}
message GroupMemberCancelMutedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
int64 operationTime = 3;
GroupMemberFullInfo mutedUser = 4;
}
message GroupMutedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
int64 operationTime = 3;
}
message GroupCancelMutedTips{
GroupInfo group = 1;
GroupMemberFullInfo opUser = 2;
int64 operationTime = 3;
}
//////////////////////friend/////////////////////
//message FriendInfo{
// UserInfo OwnerUser = 1;
// string Remark = 2;
// uint64 CreateTime = 3;
// UserInfo FriendUser = 4;
//}
message FriendApplication{
int64 addTime = 1;
string addSource = 2;
string addWording = 3;
}
message FromToUserID{
string fromUserID = 1;
string toUserID = 2;
}
//FromUserID apply to add ToUserID
message FriendApplicationTips{
FromToUserID fromToUserID = 1;
}
//FromUserID accept or reject ToUserID
message FriendApplicationApprovedTips{
FromToUserID fromToUserID = 1;
string handleMsg = 2;
}
//FromUserID accept or reject ToUserID
message FriendApplicationRejectedTips{
FromToUserID fromToUserID = 1;
string handleMsg = 2;
}
// FromUserID Added a friend ToUserID
message FriendAddedTips{
FriendInfo friend = 1;
int64 operationTime = 2;
PublicUserInfo opUser = 3; //who do this
}
// FromUserID deleted a friend ToUserID
message FriendDeletedTips{
FromToUserID fromToUserID = 1;
}
message BlackAddedTips{
FromToUserID fromToUserID = 1;
}
message BlackDeletedTips{
FromToUserID fromToUserID = 1;
}
message FriendInfoChangedTips{
FromToUserID fromToUserID = 1;
}
//////////////////////user/////////////////////
message UserInfoUpdatedTips{
string userID = 1;
}
//////////////////////conversation/////////////////////
message ConversationUpdateTips{
string UserID = 1;
}
message ConversationSetPrivateTips{
string recvID = 1;
string sendID = 2;
bool isPrivate = 3;
}
///cms
message RequestPagination {
int32 pageNumber = 1;
int32 showNumber = 2;
}
message ResponsePagination {
int32 CurrentPage = 5;
int32 ShowNumber = 6;
}
///////////////////signal//////////////
message SignalReq {
oneof payload {
SignalInviteReq invite = 1;
SignalInviteInGroupReq inviteInGroup= 2;
SignalCancelReq cancel = 3;
SignalAcceptReq accept = 4;
SignalHungUpReq hungUp = 5;
SignalRejectReq reject = 6;
}
}
message SignalResp {
oneof payload {
SignalInviteReply invite = 1;
SignalInviteInGroupReply inviteInGroup= 2;
SignalCancelReply cancel = 3;
SignalAcceptReply accept = 4;
SignalHungUpReply hungUp = 5;
SignalRejectReply reject = 6;
}
}
message InvitationInfo {
string inviterUserID = 1;
repeated string inviteeUserIDList = 2;
string customData = 3;
string groupID = 4;
string roomID = 5;
int32 timeout = 6;
string mediaType = 7;
int32 platformID = 8;
int32 sessionType = 9;
}
message ParticipantMetaData{
GroupInfo groupInfo = 1;
GroupMemberFullInfo groupMemberInfo = 2;
PublicUserInfo userInfo = 3;
}
message SignalInviteReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalInviteReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalInviteInGroupReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalInviteInGroupReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalCancelReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
}
message SignalCancelReply {
}
message SignalAcceptReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
int32 opUserPlatformID = 5;
}
message SignalAcceptReply {
string token = 1;
string roomID = 2;
string liveURL = 3;
}
message SignalHungUpReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
}
message SignalHungUpReply {
}
message SignalRejectReq {
string opUserID = 1;
InvitationInfo invitation = 2;
OfflinePushInfo offlinePushInfo = 3;
ParticipantMetaData participant = 4;
int32 opUserPlatformID = 5;
}
message SignalRejectReply {
}
message DelMsgListReq{
string opUserID = 1;
string userID = 2;
repeated uint32 seqList = 3;
string operationID = 4;
}
message DelMsgListResp{
int32 errCode = 1;
string errMsg = 2;
}
File diff suppressed because it is too large Load Diff
+93
View File
@@ -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
+316
View File
@@ -0,0 +1,316 @@
syntax = "proto3";
import "Open_IM/pkg/proto/sdk_ws/ws.proto";
option go_package = "./user;user";
package user;
message CommonResp{
int32 errCode = 1;
string errMsg = 2;
}
message DeleteUsersReq{
repeated string DeleteUserIDList = 2;
string OpUserID = 3;
string OperationID = 4;
}
message DeleteUsersResp{
CommonResp CommonResp = 1;
repeated string FailedUserIDList = 2;
}
message GetAllUserIDReq{
string opUserID = 1;
string operationID = 2;
}
message GetAllUserIDResp{
CommonResp CommonResp = 1;
repeated string UserIDList = 2;
}
message AccountCheckReq{
repeated string CheckUserIDList = 1;
string OpUserID = 2;
string OperationID = 3;
}
message AccountCheckResp{
CommonResp commonResp = 1;
message SingleUserStatus {
string userID = 1;
string accountStatus = 2;
}
repeated SingleUserStatus ResultList = 2;
}
message GetUserInfoReq{
repeated string userIDList = 1;
string OpUserID = 2;
string OperationID = 3;
}
message GetUserInfoResp{
CommonResp commonResp = 1;
repeated server_api_params.UserInfo UserInfoList = 3;
}
message UpdateUserInfoReq{
server_api_params.UserInfo UserInfo = 1;
string OpUserID = 2;
string operationID = 3;
}
message UpdateUserInfoResp{
CommonResp commonResp = 1;
}
message Conversation{
string OwnerUserID = 1;
string ConversationID = 2;
int32 RecvMsgOpt = 3;
int32 ConversationType = 4;
string UserID = 5;
string GroupID = 6;
int32 UnreadCount = 7;
int64 DraftTextTime = 8;
bool IsPinned = 9;
string AttachedInfo = 10;
bool IsPrivateChat = 11;
string Ex = 12;
}
message SetConversationReq{
Conversation Conversation = 1;
int32 notificationType = 2;
string OperationID = 3;
}
message SetConversationResp{
CommonResp commonResp = 1;
}
message SetRecvMsgOptReq {
string OwnerUserID = 1;
string ConversationID = 2;
int32 RecvMsgOpt = 3;
int32 notificationType = 4;
string OperationID = 5;
}
message SetRecvMsgOptResp {
CommonResp commonResp = 1;
}
message GetConversationReq{
string ConversationID = 1;
string OwnerUserID = 2;
string OperationID = 3;
}
message GetConversationResp{
CommonResp commonResp = 1;
Conversation Conversation = 2;
}
message GetConversationsReq{
string OwnerUserID = 1;
repeated string ConversationIDs = 2;
string OperationID = 3;
}
message GetConversationsResp{
CommonResp commonResp = 1;
repeated Conversation Conversations = 2;
}
message GetAllConversationsReq{
string OwnerUserID = 1;
string OperationID = 2;
}
message GetAllConversationsResp{
CommonResp commonResp = 1;
repeated Conversation Conversations = 2;
}
message BatchSetConversationsReq{
repeated Conversation Conversations = 1;
string OwnerUserID = 2;
int32 notificationType = 3;
string OperationID = 4;
}
message BatchSetConversationsResp{
CommonResp commonResp = 1;
repeated string Success = 2;
repeated string Failed = 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;
string OpUserId = 6;
}
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;
string OpUserId = 5;
}
message AddUserResp{
CommonResp CommonResp = 1;
}
message BlockUserReq{
string UserId = 1;
string EndDisableTime = 2;
string OperationID = 3;
string OpUserId = 4;
}
message BlockUserResp{
CommonResp CommonResp = 1;
}
message UnBlockUserReq{
string UserId = 1;
string OperationID = 2;
string OpUserId = 3;
}
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;
string OpUserId = 3;
}
message DeleteUserResp {
CommonResp CommonResp = 1;
}
service user {
rpc GetUserInfo(GetUserInfoReq) returns(GetUserInfoResp);
rpc UpdateUserInfo(UpdateUserInfoReq) returns(UpdateUserInfoResp);
rpc DeleteUsers(DeleteUsersReq)returns(DeleteUsersResp);
rpc GetAllUserID(GetAllUserIDReq)returns(GetAllUserIDResp);
rpc AccountCheck(AccountCheckReq)returns(AccountCheckResp);
rpc GetConversation(GetConversationReq)returns(GetConversationResp);
rpc GetAllConversations(GetAllConversationsReq)returns(GetAllConversationsResp);
rpc GetConversations(GetConversationsReq)returns(GetConversationsResp);
rpc BatchSetConversations(BatchSetConversationsReq)returns(BatchSetConversationsResp);
rpc SetConversation(SetConversationReq)returns(SetConversationResp);
rpc SetRecvMsgOpt(SetRecvMsgOptReq)returns(SetRecvMsgOptResp);
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);
}
+32
View File
@@ -0,0 +1,32 @@
package statistics
import (
"Open_IM/pkg/common/log"
"time"
)
type Statistics struct {
Count *uint64
ModuleName string
PrintArgs string
SleepTime int
}
func (s *Statistics) output() {
t := time.NewTicker(time.Duration(s.SleepTime) * time.Second)
defer t.Stop()
var sum uint64
for {
sum = *s.Count
select {
case <-t.C:
}
log.NewWarn("", " system stat ", s.ModuleName, s.PrintArgs, *s.Count-sum, "total:", *s.Count)
}
}
func NewStatistics(count *uint64, moduleName, printArgs string, sleepTime int) *Statistics {
p := &Statistics{Count: count, ModuleName: moduleName, SleepTime: sleepTime, PrintArgs: printArgs}
go p.output()
return p
}
+24
View File
@@ -0,0 +1,24 @@
package utils
import (
"net/http"
"github.com/gin-gonic/gin"
)
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()
}
}
+39
View File
@@ -0,0 +1,39 @@
package utils
import (
"Open_IM/pkg/common/constant"
"fmt"
"math/rand"
"os"
"path"
"time"
)
// Determine whether the given path is a folder
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// Determine whether the given path is a file
func IsFile(path string) bool {
return !IsDir(path)
}
// Create a directory
func MkDir(path string) error {
return os.MkdirAll(path, os.ModePerm)
}
func GetNewFileNameAndContentType(fileName string, fileType int) (string, string) {
suffix := path.Ext(fileName)
newName := fmt.Sprintf("%d-%d%s", time.Now().UnixNano(), rand.Int(), fileName)
contentType := ""
if fileType == constant.ImageType {
contentType = "image/" + suffix[1:]
}
return newName, contentType
}
+26
View File
@@ -0,0 +1,26 @@
package utils
import (
"Open_IM/pkg/common/config"
"net"
)
var ServerIP = ""
func init() {
//fixme In the configuration file, ip takes precedence, if not, get the valid network card ip of the machine
if config.Config.ServerIP != "" {
ServerIP = config.Config.ServerIP
return
}
// see https://gist.github.com/jniltinho/9787946#gistcomment-3019898
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
panic(err.Error())
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ServerIP = localAddr.IP.String()
}
+56
View File
@@ -0,0 +1,56 @@
package utils
import (
"errors"
"github.com/nfnt/resize"
"golang.org/x/image/bmp"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
)
func GenSmallImage(src, dst string) error {
fIn, _ := os.Open(src)
defer fIn.Close()
fOut, _ := os.Create(dst)
defer fOut.Close()
if err := scale(fIn, fOut, 0, 0, 0); err != nil {
return err
}
return nil
}
func scale(in io.Reader, out io.Writer, width, height, quality int) error {
origin, fm, err := image.Decode(in)
if err != nil {
return err
}
if width == 0 || height == 0 {
width = origin.Bounds().Max.X / 2
height = origin.Bounds().Max.Y / 2
}
if quality == 0 {
quality = 25
}
canvas := resize.Thumbnail(uint(width), uint(height), origin, resize.Lanczos3)
switch fm {
case "jpeg":
return jpeg.Encode(out, canvas, &jpeg.Options{quality})
case "png":
return png.Encode(out, canvas)
case "gif":
return gif.Encode(out, canvas, &gif.Options{})
case "bmp":
return bmp.Encode(out, canvas)
default:
return errors.New("ERROR FORMAT")
}
return nil
}
+129
View File
@@ -0,0 +1,129 @@
package utils
import (
"encoding/json"
"sync"
)
type Map struct {
sync.RWMutex
m map[interface{}]interface{}
}
func (m *Map) init() {
if m.m == nil {
m.m = make(map[interface{}]interface{})
}
}
func (m *Map) UnsafeGet(key interface{}) interface{} {
if m.m == nil {
return nil
} else {
return m.m[key]
}
}
func (m *Map) Get(key interface{}) interface{} {
m.RLock()
defer m.RUnlock()
return m.UnsafeGet(key)
}
func (m *Map) UnsafeSet(key interface{}, value interface{}) {
m.init()
m.m[key] = value
}
func (m *Map) Set(key interface{}, value interface{}) {
m.Lock()
defer m.Unlock()
m.UnsafeSet(key, value)
}
func (m *Map) TestAndSet(key interface{}, value interface{}) interface{} {
m.Lock()
defer m.Unlock()
m.init()
if v, ok := m.m[key]; ok {
return v
} else {
m.m[key] = value
return nil
}
}
func (m *Map) UnsafeDel(key interface{}) {
m.init()
delete(m.m, key)
}
func (m *Map) Del(key interface{}) {
m.Lock()
defer m.Unlock()
m.UnsafeDel(key)
}
func (m *Map) UnsafeLen() int {
if m.m == nil {
return 0
} else {
return len(m.m)
}
}
func (m *Map) Len() int {
m.RLock()
defer m.RUnlock()
return m.UnsafeLen()
}
func (m *Map) UnsafeRange(f func(interface{}, interface{})) {
if m.m == nil {
return
}
for k, v := range m.m {
f(k, v)
}
}
func (m *Map) RLockRange(f func(interface{}, interface{})) {
m.RLock()
defer m.RUnlock()
m.UnsafeRange(f)
}
func (m *Map) LockRange(f func(interface{}, interface{})) {
m.Lock()
defer m.Unlock()
m.UnsafeRange(f)
}
func MapToJsonString(param map[string]interface{}) string {
dataType, _ := json.Marshal(param)
dataString := string(dataType)
return dataString
}
func MapIntToJsonString(param map[string]int32) string {
dataType, _ := json.Marshal(param)
dataString := string(dataType)
return dataString
}
func JsonStringToMap(str string) (tempMap map[string]int32) {
_ = json.Unmarshal([]byte(str), &tempMap)
return tempMap
}
func GetSwitchFromOptions(Options map[string]bool, key string) (result bool) {
if flag, ok := Options[key]; !ok || flag {
return true
}
return false
}
func SetSwitchFromOptions(options map[string]bool, key string, value bool) {
if options == nil {
options = make(map[string]bool, 5)
}
options[key] = value
}
+13
View File
@@ -0,0 +1,13 @@
package utils
import (
"crypto/md5"
"encoding/hex"
)
func Md5(s string) string {
h := md5.New()
h.Write([]byte(s))
cipher := h.Sum(nil)
return hex.EncodeToString(cipher)
}

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