v3 - main to cut out
This commit is contained in:
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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),
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
//// })
|
||||
////}
|
||||
@@ -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, ""
|
||||
}
|
||||
@@ -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){
|
||||
//
|
||||
//}
|
||||
Reference in New Issue
Block a user