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

# Conflicts:
#	internal/rpc/group/callback.go
This commit is contained in:
withchao
2023-02-10 19:18:29 +08:00
110 changed files with 788 additions and 36046 deletions
-25
View File
@@ -37,10 +37,6 @@ type config struct {
GinPort []int `yaml:"openImApiPort"`
ListenIP string `yaml:"listenIP"`
}
CmsApi struct {
GinPort []int `yaml:"openImCmsApiPort"`
ListenIP string `yaml:"listenIP"`
}
Sdk struct {
WsPort []int `yaml:"openImSdkWsPort"`
DataDir []string `yaml:"dataDir"`
@@ -131,8 +127,6 @@ type config struct {
OpenImGroupPort []int `yaml:"openImGroupPort"`
OpenImAuthPort []int `yaml:"openImAuthPort"`
OpenImPushPort []int `yaml:"openImPushPort"`
OpenImAdminCmsPort []int `yaml:"openImAdminCmsPort"`
OpenImOfficePort []int `yaml:"openImOfficePort"`
OpenImConversationPort []int `yaml:"openImConversationPort"`
OpenImCachePort []int `yaml:"openImCachePort"`
OpenImRealTimeCommPort []int `yaml:"openImRealTimeCommPort"`
@@ -146,8 +140,6 @@ type config struct {
OpenImRelayName string `yaml:"openImRelayName"`
OpenImGroupName string `yaml:"openImGroupName"`
OpenImAuthName string `yaml:"openImAuthName"`
OpenImAdminCMSName string `yaml:"openImAdminCMSName"`
OpenImOfficeName string `yaml:"openImOfficeName"`
OpenImConversationName string `yaml:"openImConversationName"`
OpenImCacheName string `yaml:"openImCacheName"`
OpenImRealTimeCommName string `yaml:"openImRealTimeCommName"`
@@ -473,16 +465,6 @@ type config struct {
CloseTips string `yaml:"closeTips"`
} `yaml:"defaultTips"`
} `yaml:"conversationSetPrivate"`
WorkMomentsNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"workMomentsNotification"`
JoinDepartmentNotification struct {
Conversation PConversation `yaml:"conversation"`
OfflinePush POfflinePush `yaml:"offlinePush"`
DefaultTips PDefaultTips `yaml:"defaultTips"`
} `yaml:"joinDepartmentNotification"`
Signal struct {
OfflinePush struct {
Title string `yaml:"title"`
@@ -490,9 +472,6 @@ type config struct {
} `yaml:"signal"`
}
WorkMoment struct {
OnlyFriendCanSee bool `yaml:"onlyFriendCanSee"`
} `yaml:"workMoment"`
Rtc struct {
SignalTimeout string `yaml:"signalTimeout"`
} `yaml:"rtc"`
@@ -506,11 +485,7 @@ type config struct {
GroupPrometheusPort []int `yaml:"groupPrometheusPort"`
AuthPrometheusPort []int `yaml:"authPrometheusPort"`
PushPrometheusPort []int `yaml:"pushPrometheusPort"`
AdminCmsPrometheusPort []int `yaml:"adminCmsPrometheusPort"`
OfficePrometheusPort []int `yaml:"officePrometheusPort"`
OrganizationPrometheusPort []int `yaml:"organizationPrometheusPort"`
ConversationPrometheusPort []int `yaml:"conversationPrometheusPort"`
CachePrometheusPort []int `yaml:"cachePrometheusPort"`
RealTimeCommPrometheusPort []int `yaml:"realTimeCommPrometheusPort"`
MessageTransferPrometheusPort []int `yaml:"messageTransferPrometheusPort"`
} `yaml:"prometheus"`
-14
View File
@@ -94,9 +94,6 @@ const (
ConversationPrivateChatNotification = 1701
ConversationUnreadNotification = 1702
WorkMomentNotificationBegin = 1900
WorkMomentNotification = 1901
BusinessNotificationBegin = 2000
BusinessNotification = 2001
BusinessNotificationEnd = 2099
@@ -218,17 +215,6 @@ const (
VideoType = 2
ImageType = 3
// workMoment permission
WorkMomentPublic = 0
WorkMomentPrivate = 1
WorkMomentPermissionCanSee = 2
WorkMomentPermissionCantSee = 3
// workMoment sdk notification type
WorkMomentCommentNotification = 0
WorkMomentLikeNotification = 1
WorkMomentAtUserNotification = 2
// sendMsgStaus
MsgStatusNotExist = 0
MsgIsSending = 1
+5
View File
@@ -0,0 +1,5 @@
package constant
const (
ShowNumber = 1000
)
+5
View File
@@ -9,6 +9,11 @@ import (
"time"
)
const (
extendMsgSetCache = "EXTEND_MSG_SET_CACHE:"
extendMsgCache = "EXTEND_MSG_CACHE:"
)
type ExtendMsgSetCache struct {
expireTime time.Duration
rcClient *rockscache.Client
+43 -29
View File
@@ -1,42 +1,15 @@
package cache
import (
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/relation"
"Open_IM/pkg/common/log"
"Open_IM/pkg/common/tracelog"
"Open_IM/pkg/utils"
"context"
"encoding/json"
"math/big"
"sort"
"strconv"
"github.com/dtm-labs/rockscache"
"time"
)
const (
//userInfoCache = "USER_INFO_CACHE:"
//friendRelationCache = "FRIEND_RELATION_CACHE:"
blackListCache = "BLACK_LIST_CACHE:"
//groupCache = "GROUP_CACHE:"
//groupInfoCache = "GROUP_INFO_CACHE:"
//groupOwnerIDCache = "GROUP_OWNER_ID:"
//joinedGroupListCache = "JOINED_GROUP_LIST_CACHE:"
//groupMemberInfoCache = "GROUP_MEMBER_INFO_CACHE:"
//groupAllMemberInfoCache = "GROUP_ALL_MEMBER_INFO_CACHE:"
//allFriendInfoCache = "ALL_FRIEND_INFO_CACHE:"
//joinedSuperGroupListCache = "JOINED_SUPER_GROUP_LIST_CACHE:"
//groupMemberListHashCache = "GROUP_MEMBER_LIST_HASH_CACHE:"
//groupMemberNumCache = "GROUP_MEMBER_NUM_CACHE:"
conversationCache = "CONVERSATION_CACHE:"
conversationIDListCache = "CONVERSATION_ID_LIST_CACHE:"
extendMsgSetCache = "EXTEND_MSG_SET_CACHE:"
extendMsgCache = "EXTEND_MSG_CACHE:"
)
const scanCount = 3000
const RandomExpireAdjustment = 0.2
func (rc *RcClient) DelKeys() {
for _, key := range []string{"GROUP_CACHE:", "FRIEND_RELATION_CACHE", "BLACK_LIST_CACHE:", "USER_INFO_CACHE:", "GROUP_INFO_CACHE", groupOwnerIDCache, joinedGroupListCache,
@@ -68,3 +41,44 @@ func (rc *RcClient) DelKeys() {
}
}
}
func GetCache[T any](ctx context.Context, rcClient *rockscache.Client, key string, expire time.Duration, fn func(ctx context.Context) (T, error)) (T, error) {
var t T
var write bool
v, err := rcClient.Fetch(key, expire, func() (s string, err error) {
t, err = fn(ctx)
if err != nil {
return "", err
}
bs, err := json.Marshal(t)
if err != nil {
return "", utils.Wrap(err, "")
}
write = true
return string(bs), nil
})
if err != nil {
return t, err
}
if write {
return t, nil
}
err = json.Unmarshal([]byte(v), &t)
if err != nil {
return t, utils.Wrap(err, "")
}
return t, nil
}
func GetCacheFor[E any, T any](ctx context.Context, list []E, fn func(ctx context.Context, item E) (T, error)) ([]T, error) {
rs := make([]T, 0, len(list))
for _, e := range list {
r, err := fn(ctx, e)
if err != nil {
return nil, err
}
rs = append(rs, r)
}
return rs, nil
}
-49
View File
@@ -1,49 +0,0 @@
package cache
import (
"Open_IM/pkg/utils"
"context"
"encoding/json"
"github.com/dtm-labs/rockscache"
"time"
)
func GetCache[T any](ctx context.Context, rcClient *rockscache.Client, key string, expire time.Duration, fn func(ctx context.Context) (T, error)) (T, error) {
var t T
var write bool
v, err := rcClient.Fetch(key, expire, func() (s string, err error) {
t, err = fn(ctx)
if err != nil {
return "", err
}
bs, err := json.Marshal(t)
if err != nil {
return "", utils.Wrap(err, "")
}
write = true
return string(bs), nil
})
if err != nil {
return t, err
}
if write {
return t, nil
}
err = json.Unmarshal([]byte(v), &t)
if err != nil {
return t, utils.Wrap(err, "")
}
return t, nil
}
func GetCacheFor[E any, T any](ctx context.Context, list []E, fn func(ctx context.Context, item E) (T, error)) ([]T, error) {
rs := make([]T, 0, len(list))
for _, e := range list {
r, err := fn(ctx, e)
if err != nil {
return nil, err
}
rs = append(rs, r)
}
return rs, nil
}
-142
View File
@@ -1,142 +0,0 @@
package controller
import (
"Open_IM/pkg/common/db/relation"
"gorm.io/gorm"
"time"
)
type AdminCMSInterface interface {
GetActiveUserNum(from, to time.Time) (num int64, err error)
GetIncreaseUserNum(from, to time.Time) (num int64, err error)
GetTotalUserNum() (num int64, err error)
GetTotalUserNumByDate(to time.Time) (num int64, err error)
GetSingleChatMessageNum(from, to time.Time) (num int64, err error)
GetGroupMessageNum(from, to time.Time) (num int64, err error)
GetIncreaseGroupNum(from, to time.Time) (num int64, err error)
GetTotalGroupNum() (num int64, err error)
GetGroupNum(to time.Time) (num int64, err error)
GetActiveGroups(from, to time.Time, limit int) (activeGroups []*relation.ActiveGroup, err error)
GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error)
}
type AdminCMSController struct {
database AdminCMSDatabaseInterface
}
func NewAdminCMSController(db *gorm.DB) AdminCMSInterface {
adminCMSController := &AdminCMSController{
database: newAdminCMSDatabase(db),
}
return adminCMSController
}
func newAdminCMSDatabase(db *gorm.DB) AdminCMSDatabaseInterface {
return &AdminCMSDatabase{Statistics: relation.NewStatistics(db)}
}
func (admin *AdminCMSController) GetActiveUserNum(from, to time.Time) (num int64, err error) {
return admin.database.GetActiveUserNum(from, to)
}
func (admin *AdminCMSController) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
return admin.database.GetIncreaseUserNum(from, to)
}
func (admin *AdminCMSController) GetTotalUserNum() (num int64, err error) {
return admin.database.GetTotalUserNum()
}
func (admin *AdminCMSController) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
return admin.database.GetTotalUserNumByDate(to)
}
func (admin *AdminCMSController) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
return admin.GetSingleChatMessageNum(from, to)
}
func (admin *AdminCMSController) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
return admin.database.GetGroupMessageNum(from, to)
}
func (admin *AdminCMSController) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
return admin.database.GetIncreaseGroupNum(from, to)
}
func (admin *AdminCMSController) GetTotalGroupNum() (num int64, err error) {
return admin.database.GetTotalGroupNum()
}
func (admin *AdminCMSController) GetGroupNum(to time.Time) (num int64, err error) {
return admin.database.GetGroupNum(to)
}
func (admin *AdminCMSController) GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error) {
return admin.database.GetActiveGroups(from, to, limit)
}
func (admin *AdminCMSController) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error) {
return admin.database.GetActiveUsers(from, to, limit)
}
type AdminCMSDatabaseInterface interface {
GetActiveUserNum(from, to time.Time) (num int64, err error)
GetIncreaseUserNum(from, to time.Time) (num int64, err error)
GetTotalUserNum() (num int64, err error)
GetTotalUserNumByDate(to time.Time) (num int64, err error)
GetSingleChatMessageNum(from, to time.Time) (num int64, err error)
GetGroupMessageNum(from, to time.Time) (num int64, err error)
GetIncreaseGroupNum(from, to time.Time) (num int64, err error)
GetTotalGroupNum() (num int64, err error)
GetGroupNum(to time.Time) (num int64, err error)
GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error)
GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error)
}
type AdminCMSDatabase struct {
Statistics *relation.Statistics
}
func (admin *AdminCMSDatabase) GetActiveUserNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetActiveUserNum(from, to)
}
func (admin *AdminCMSDatabase) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetIncreaseUserNum(from, to)
}
func (admin *AdminCMSDatabase) GetTotalUserNum() (num int64, err error) {
return admin.Statistics.GetTotalUserNum()
}
func (admin *AdminCMSDatabase) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
return admin.Statistics.GetTotalUserNumByDate(to)
}
func (admin *AdminCMSDatabase) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetSingleChatMessageNum(from, to)
}
func (admin *AdminCMSDatabase) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetGroupMessageNum(from, to)
}
func (admin *AdminCMSDatabase) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
return admin.Statistics.GetIncreaseGroupNum(from, to)
}
func (admin *AdminCMSDatabase) GetTotalGroupNum() (num int64, err error) {
return admin.Statistics.GetTotalGroupNum()
}
func (admin *AdminCMSDatabase) GetGroupNum(to time.Time) (num int64, err error) {
return admin.Statistics.GetGroupNum(to)
}
func (admin *AdminCMSDatabase) GetActiveGroups(from, to time.Time, limit int) ([]*relation.ActiveGroup, error) {
return admin.Statistics.GetActiveGroups(from, to, limit)
}
func (admin *AdminCMSDatabase) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*relation.ActiveUser, err error) {
return admin.Statistics.GetActiveUsers(from, to, limit)
}
+23
View File
@@ -0,0 +1,23 @@
package controller
import (
pbMsg "Open_IM/pkg/proto/msg"
"context"
)
type MsgInterface interface {
BatchInsertChat2DB(ctx context.Context, userID string, msgList []*pbMsg.MsgDataToMQ, currentMaxSeq uint64) error
BatchInsertChat2Cache(ctx context.Context, insertID string, msgList []*pbMsg.MsgDataToMQ) (error, uint64)
DelMsgBySeqList(ctx context.Context, userID string, seqList []uint32) (totalUnExistSeqList []uint32, err error)
// logic delete
DelMsgLogic(ctx context.Context, userID string, seqList []uint32) error
DelMsgBySeqListInOneDoc(ctx context.Context, docID string, seqList []uint32) (unExistSeqList []uint32, err error)
ReplaceMsgToBlankByIndex(docID string, index int) (replaceMaxSeq uint32, err error)
}
type MsgDatabaseInterface interface {
BatchInsertChat2DB(ctx context.Context, userID string, msgList []*pbMsg.MsgDataToMQ, currentMaxSeq uint64) error
BatchInsertChat2Cache(ctx context.Context, insertID string, msgList []*pbMsg.MsgDataToMQ) (error, uint64)
DelMsgBySeqList(ctx context.Context, userID string, seqList []uint32) (totalUnExistSeqList []uint32, err error)
}
+5 -5
View File
@@ -30,11 +30,11 @@ type UserController struct {
}
// 获取指定用户的信息 如有userID未找到 也返回错误
func (u *UserController) FindWithError(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserController) FindWithError(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
return u.database.FindWithError(ctx, userIDs)
}
func (u *UserController) Find(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserController) Find(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
return u.database.Find(ctx, userIDs)
}
func (u *UserController) Create(ctx context.Context, users []*relationTb.UserModel) error {
@@ -90,7 +90,7 @@ func newUserDatabase(db *gorm.DB) *UserDatabase {
}
// 获取指定用户的信息 如有userID未找到 也返回错误
func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
users, err = u.user.Find(ctx, userIDs)
if err != nil {
return
@@ -102,7 +102,7 @@ func (u *UserDatabase) FindWithError(ctx context.Context, userIDs []string) (use
}
// 获取指定用户的信息 如有userID未找到 不返回错误
func (u *UserDatabase) Find(ctx context.Context, userIDs []string) (users []*relation2.UserModel, err error) {
func (u *UserDatabase) Find(ctx context.Context, userIDs []string) (users []*relationTb.UserModel, err error) {
users, err = u.user.Find(ctx, userIDs)
return
}
@@ -123,7 +123,7 @@ func (u *UserDatabase) UpdateByMap(ctx context.Context, userID string, args map[
}
// 获取,如果没找到,不返回错误
func (u *UserDatabase) Page(ctx context.Context, showNumber, pageNumber int32) (users []*relation2.UserModel, count int64, err error) {
func (u *UserDatabase) Page(ctx context.Context, showNumber, pageNumber int32) (users []*relationTb.UserModel, count int64, err error) {
return u.user.Page(ctx, showNumber, pageNumber)
}
-100
View File
@@ -1,100 +0,0 @@
package relation
import (
"Open_IM/pkg/common/config"
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Mysql struct {
gormConn *gorm.DB
}
func (m *Mysql) GormConn() *gorm.DB {
return m.gormConn
}
func (m *Mysql) SetGormConn(gormConn *gorm.DB) {
m.gormConn = gormConn
}
func (m *Mysql) InitConn() *Mysql {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], "mysql")
var db *gorm.DB
db, err := gorm.Open(mysql.Open(dsn), nil)
if err != nil {
time.Sleep(time.Duration(30) * time.Second)
db, err = gorm.Open(mysql.Open(dsn), nil)
if err != nil {
panic(err.Error() + " open failed " + dsn)
}
}
sql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s default charset utf8 COLLATE utf8_general_ci;", config.Config.Mysql.DBDatabaseName)
err = db.Exec(sql).Error
if err != nil {
panic(err.Error() + " Exec failed:" + sql)
}
dsn = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
config.Config.Mysql.DBUserName, config.Config.Mysql.DBPassword, config.Config.Mysql.DBAddress[0], config.Config.Mysql.DBDatabaseName)
newLogger := logger.New(
Writer{},
logger.Config{
SlowThreshold: time.Duration(config.Config.Mysql.SlowThreshold) * time.Millisecond, // Slow SQL threshold
LogLevel: logger.LogLevel(config.Config.Mysql.LogLevel), // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
Colorful: true, // Disable color
},
)
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: newLogger,
})
if err != nil {
panic(err.Error() + " Open failed " + dsn)
}
sqlDB, err := db.DB()
if err != nil {
panic(err.Error() + " DB.DB() failed ")
}
sqlDB.SetConnMaxLifetime(time.Second * time.Duration(config.Config.Mysql.DBMaxLifeTime))
sqlDB.SetMaxOpenConns(config.Config.Mysql.DBMaxOpenConns)
sqlDB.SetMaxIdleConns(config.Config.Mysql.DBMaxIdleConns)
if db == nil {
panic("db is nil")
}
m.SetGormConn(db)
return m
}
//models := []interface{}{&Friend{}, &FriendRequest{}, &Group{}, &GroupMember{}, &GroupRequest{},
// &User{}, &Black{}, &ChatLog{}, &Conversation{}, &AppVersion{}}
func (m *Mysql) AutoMigrateModel(model interface{}) error {
err := m.gormConn.AutoMigrate(model)
if err != nil {
return err
}
m.gormConn.Set("gorm:table_options", "CHARSET=utf8")
m.gormConn.Set("gorm:table_options", "collation=utf8_unicode_ci")
_ = m.gormConn.Migrator().CreateTable(model)
return nil
}
type Writer struct{}
func (w Writer) Printf(format string, args ...interface{}) {
fmt.Printf(format, args...)
}
func getDBConn(db *gorm.DB, tx []any) *gorm.DB {
if len(tx) > 0 {
if txDB, ok := tx[0].(*gorm.DB); ok {
return txDB
}
}
return db
}
-101
View File
@@ -1,101 +0,0 @@
package relation
import (
"Open_IM/pkg/common/constant"
"gorm.io/gorm"
"time"
)
type Statistics struct {
DB *gorm.DB
}
func NewStatistics(db *gorm.DB) *Statistics {
return &Statistics{DB: db}
}
func (s *Statistics) getUserModel() *gorm.DB {
return s.DB.Model(&User{})
}
func (s *Statistics) getChatLogModel() *gorm.DB {
return s.DB.Model(&ChatLog{})
}
func (s *Statistics) getGroupModel() *gorm.DB {
return s.DB.Model(&Group{})
}
func (s *Statistics) GetActiveUserNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Select("count(distinct(send_id))").Where("send_time >= ? and send_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetIncreaseUserNum(from, to time.Time) (num int64, err error) {
err = s.getUserModel().Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalUserNum() (num int64, err error) {
err = s.getUserModel().Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalUserNumByDate(to time.Time) (num int64, err error) {
err = s.getUserModel().Where("create_time <= ?", to).Count(&num).Error
return num, err
}
func (s *Statistics) GetSingleChatMessageNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Where("send_time >= ? and send_time <= ? and session_type = ?", from, to, constant.SingleChatType).Count(&num).Error
return num, err
}
func (s *Statistics) GetGroupMessageNum(from, to time.Time) (num int64, err error) {
err = s.getChatLogModel().Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.GroupChatType, constant.SuperGroupChatType}).Count(&num).Error
return num, err
}
func (s *Statistics) GetIncreaseGroupNum(from, to time.Time) (num int64, err error) {
err = s.getGroupModel().Where("create_time >= ? and create_time <= ?", from, to).Count(&num).Error
return num, err
}
func (s *Statistics) GetTotalGroupNum() (num int64, err error) {
err = s.getGroupModel().Count(&num).Error
return num, err
}
func (s *Statistics) GetGroupNum(to time.Time) (num int64, err error) {
err = s.getGroupModel().Where("create_time <= ?", to).Count(&num).Error
return num, err
}
func (s *Statistics) GetActiveGroups(from, to time.Time, limit int) ([]*ActiveGroup, error) {
var activeGroups []*ActiveGroup
err := s.getChatLogModel().Select("recv_id, count(*) as message_num").Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.GroupChatType, constant.SuperGroupChatType}).Group("recv_id").Limit(limit).Order("message_num DESC").Find(&activeGroups).Error
for _, activeGroup := range activeGroups {
group := Group{
GroupID: activeGroup.ID,
}
s.getGroupModel().Where("group_id= ? ", group.GroupID).Find(&group)
activeGroup.Name = group.GroupName
}
return activeGroups, err
}
func (s *Statistics) GetActiveUsers(from, to time.Time, limit int) (activeUsers []*ActiveUser, err error) {
err = s.getChatLogModel().Select("send_id, count(*) as message_num").Where("send_time >= ? and send_time <= ? and session_type in (?)", from, to, []int{constant.SingleChatType, constant.GroupChatType, constant.SuperGroupChatType}).Group("send_id").Limit(limit).Order("message_num DESC").Find(&activeUsers).Error
for _, activeUser := range activeUsers {
user := User{
UserID: activeUser.ID,
}
err = s.getUserModel().Select("user_id, name").Find(&user).Error
if err != nil {
return nil, err
}
activeUser.Name = user.Nickname
activeUser.ID = user.UserID
}
return activeUsers, err
}
+25 -11
View File
@@ -7,9 +7,9 @@ const (
CChat = "msg"
)
type UserChatModel struct {
UID string `bson:"uid"`
Msg []MsgInfoModel `bson:"msg"`
type UserMsgDocModel struct {
DocID string `bson:"uid"`
Msg []MsgInfoModel `bson:"msg"`
}
type MsgInfoModel struct {
@@ -17,20 +17,20 @@ type MsgInfoModel struct {
Msg []byte `bson:"msg"`
}
func (UserChatModel) TableName() string {
func (UserMsgDocModel) TableName() string {
return CChat
}
func (UserChatModel) GetSingleGocMsgNum() int {
func (UserMsgDocModel) GetSingleDocMsgNum() int {
return singleGocMsgNum
}
func (u UserChatModel) getSeqUid(uid string, seq uint32) string {
func (u UserMsgDocModel) getSeqUid(uid string, seq uint32) string {
seqSuffix := seq / singleGocMsgNum
return u.indexGen(uid, seqSuffix)
}
func (u UserChatModel) getSeqUserIDList(userID string, maxSeq uint32) []string {
func (u UserMsgDocModel) getSeqUserIDList(userID string, maxSeq uint32) []string {
seqMaxSuffix := maxSeq / singleGocMsgNum
var seqUserIDList []string
for i := 0; i <= int(seqMaxSuffix); i++ {
@@ -40,16 +40,30 @@ func (u UserChatModel) getSeqUserIDList(userID string, maxSeq uint32) []string {
return seqUserIDList
}
func (UserChatModel) getSeqSuperGroupID(groupID string, seq uint32) string {
func (UserMsgDocModel) getSeqSuperGroupID(groupID string, seq uint32) string {
seqSuffix := seq / singleGocMsgNum
return superGroupIndexGen(groupID, seqSuffix)
}
func (u UserChatModel) GetSeqUid(uid string, seq uint32) string {
func (u UserMsgDocModel) GetSeqUid(uid string, seq uint32) string {
return u.getSeqUid(uid, seq)
}
func (UserChatModel) getMsgIndex(seq uint32) int {
func (u UserMsgDocModel) GetDocIDSeqsMap(uid string, seqs []uint32) map[string][]uint32 {
t := make(map[string][]uint32)
for i := 0; i < len(seqs); i++ {
seqUid := u.getSeqUid(uid, seqs[i])
if value, ok := t[seqUid]; !ok {
var temp []uint32
t[seqUid] = append(temp, seqs[i])
} else {
t[seqUid] = append(value, seqs[i])
}
}
return t
}
func (UserMsgDocModel) getMsgIndex(seq uint32) int {
seqSuffix := seq / singleGocMsgNum
var index uint32
if seqSuffix == 0 {
@@ -60,6 +74,6 @@ func (UserChatModel) getMsgIndex(seq uint32) int {
return int(index)
}
func (UserChatModel) indexGen(uid string, seqSuffix uint32) string {
func (UserMsgDocModel) indexGen(uid string, seqSuffix uint32) string {
return uid + ":" + strconv.FormatInt(int64(seqSuffix), 10)
}
-42
View File
@@ -1,42 +0,0 @@
package unrelation
import "context"
const (
CTag = "tag"
CSendLog = "send_log"
)
type TagModel struct {
UserID string `bson:"user_id"`
TagID string `bson:"tag_id"`
TagName string `bson:"tag_name"`
UserList []string `bson:"user_list"`
}
func (TagModel) TableName() string {
return CTag
}
type TagSendLogModel struct {
UserList []CommonUserModel `bson:"tag_list"`
SendID string `bson:"send_id"`
SenderPlatformID int32 `bson:"sender_platform_id"`
Content string `bson:"content"`
SendTime int64 `bson:"send_time"`
}
func (TagSendLogModel) TableName() string {
return CSendLog
}
type TagModelInterface interface {
GetUserTags(ctx context.Context, userID string) ([]TagModel, error)
CreateTag(ctx context.Context, userID, tagName string, userList []string) error
GetTagByID(ctx context.Context, userID, tagID string) (TagModel, error)
DeleteTag(ctx context.Context, userID, tagID string) error
SetTag(ctx context.Context, userID, tagID, newName string, increaseUserIDList []string, reduceUserIDList []string) error
GetUserIDListByTagID(ctx context.Context, userID, tagID string) ([]string, error)
SaveTagSendLog(ctx context.Context, tagSendLog *TagSendLogModel) error
GetTagSendLogs(ctx context.Context, userID string, showNumber, pageNumber int32) ([]TagSendLogModel, error)
}
@@ -1,48 +0,0 @@
package unrelation
import "context"
const (
CWorkMoment = "work_moment"
)
type WorkMoment struct {
WorkMomentID string `bson:"work_moment_id"`
UserID string `bson:"user_id"`
UserName string `bson:"user_name"`
FaceURL string `bson:"face_url"`
Content string `bson:"content"`
LikeUserList []*CommonUserModel `bson:"like_user_list"`
AtUserList []*CommonUserModel `bson:"at_user_list"`
PermissionUserList []*CommonUserModel `bson:"permission_user_list"`
Comments []*CommonUserModel `bson:"comments"`
PermissionUserIDList []string `bson:"permission_user_id_list"`
Permission int32 `bson:"permission"`
CreateTime int32 `bson:"create_time"`
}
type Comment struct {
UserID string `bson:"user_id" json:"user_id"`
UserName string `bson:"user_name" json:"user_name"`
ReplyUserID string `bson:"reply_user_id" json:"reply_user_id"`
ReplyUserName string `bson:"reply_user_name" json:"reply_user_name"`
ContentID string `bson:"content_id" json:"content_id"`
Content string `bson:"content" json:"content"`
CreateTime int32 `bson:"create_time" json:"create_time"`
}
func (WorkMoment) TableName() string {
return CWorkMoment
}
type WorkMomentModelInterface interface {
CreateOneWorkMoment(ctx context.Context, workMoment *WorkMoment) error
DeleteOneWorkMoment(ctx context.Context, workMomentID string) error
DeleteComment(ctx context.Context, workMomentID, contentID, opUserID string) error
GetWorkMomentByID(ctx context.Context, workMomentID string) (*WorkMoment, error)
LikeOneWorkMoment(ctx context.Context, likeUserID, userName, workMomentID string) (*WorkMoment, bool, error)
CommentOneWorkMoment(ctx context.Context, comment *Comment, workMomentID string) (*WorkMoment, error)
GetUserSelfWorkMoments(ctx context.Context, userID string, showNumber, pageNumber int32) ([]*WorkMoment, error)
GetUserWorkMoments(ctx context.Context, opUserID, userID string, showNumber, pageNumber int32, friendIDList []string) ([]*WorkMoment, error)
GetUserFriendWorkMoments(ctx context.Context, showNumber, pageNumber int32, userID string, friendIDList []string) ([]*WorkMoment, error)
}
@@ -169,117 +169,3 @@ func (d *db.DataBases) BatchInsertChat2Cache(insertID string, msgList []*pbMsg.M
}
return utils.Wrap(err, ""), lastMaxSeq
}
//func (d *DataBases) BatchInsertChatBoth(userID string, msgList []*pbMsg.MsgDataToMQ, operationID string) (error, uint64) {
// err, lastMaxSeq := d.BatchInsertChat2Cache(userID, msgList, operationID)
// if err != nil {
// log.Error(operationID, "BatchInsertChat2Cache failed ", err.Error(), userID, len(msgList))
// return err, 0
// }
// for {
// if runtime.NumGoroutine() > 50000 {
// log.NewWarn(operationID, "too many NumGoroutine ", runtime.NumGoroutine())
// time.Sleep(10 * time.Millisecond)
// } else {
// break
// }
// }
// return nil, lastMaxSeq
//}
//
//func (d *DataBases) BatchInsertChat(userID string, msgList []*pbMsg.MsgDataToMQ, operationID string) error {
// newTime := getCurrentTimestampByMill()
// if len(msgList) > GetSingleGocMsgNum() {
// return errors.New("too large")
// }
// isInit := false
// currentMaxSeq, err := d.GetUserMaxSeq(userID)
// if err == nil {
//
// } else if err == go_redis.Nil {
// isInit = true
// currentMaxSeq = 0
// } else {
// return utils.Wrap(err, "")
// }
// var remain uint64
// //if currentMaxSeq < uint64(GetSingleGocMsgNum()) {
// // remain = uint64(GetSingleGocMsgNum()-1) - (currentMaxSeq % uint64(GetSingleGocMsgNum()))
// //} else {
// // remain = uint64(GetSingleGocMsgNum()) - ((currentMaxSeq - (uint64(GetSingleGocMsgNum()) - 1)) % uint64(GetSingleGocMsgNum()))
// //}
//
// blk0 := uint64(GetSingleGocMsgNum() - 1)
// if currentMaxSeq < uint64(GetSingleGocMsgNum()) {
// remain = blk0 - currentMaxSeq
// } else {
// excludeBlk0 := currentMaxSeq - blk0
// remain = (uint64(GetSingleGocMsgNum()) - (excludeBlk0 % uint64(GetSingleGocMsgNum()))) % uint64(GetSingleGocMsgNum())
// }
//
// insertCounter := uint64(0)
// msgListToMongo := make([]MsgInfo, 0)
// msgListToMongoNext := make([]MsgInfo, 0)
// seqUid := ""
// seqUidNext := ""
// log.Debug(operationID, "remain ", remain, "insertCounter ", insertCounter, "currentMaxSeq ", currentMaxSeq, userID, len(msgList))
// //4998 remain ==1
// //4999
// for _, m := range msgList {
// log.Debug(operationID, "msg node ", m.String(), m.MsgData.ClientMsgID)
// currentMaxSeq++
// sMsg := MsgInfo{}
// sMsg.SendTime = m.MsgData.SendTime
// m.MsgData.Seq = uint32(currentMaxSeq)
// if sMsg.Msg, err = proto.Marshal(m.MsgData); err != nil {
// return utils.Wrap(err, "")
// }
// if isInit {
// msgListToMongoNext = append(msgListToMongoNext, sMsg)
// seqUidNext = getSeqUid(userID, uint32(currentMaxSeq))
// log.Debug(operationID, "msgListToMongoNext ", seqUidNext, m.MsgData.Seq, m.MsgData.ClientMsgID, insertCounter, remain)
// continue
// }
// if insertCounter < remain {
// msgListToMongo = append(msgListToMongo, sMsg)
// insertCounter++
// seqUid = getSeqUid(userID, uint32(currentMaxSeq))
// log.Debug(operationID, "msgListToMongo ", seqUid, m.MsgData.Seq, m.MsgData.ClientMsgID, insertCounter, remain)
// } else {
// msgListToMongoNext = append(msgListToMongoNext, sMsg)
// seqUidNext = getSeqUid(userID, uint32(currentMaxSeq))
// log.Debug(operationID, "msgListToMongoNext ", seqUidNext, m.MsgData.Seq, m.MsgData.ClientMsgID, insertCounter, remain)
// }
// }
// // ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
//
// ctx := context.Background()
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
//
// if seqUid != "" {
// filter := bson.M{"uid": seqUid}
// log.NewDebug(operationID, "filter ", seqUid, "list ", msgListToMongo)
// err := c.FindOneAndUpdate(ctx, filter, bson.M{"$push": bson.M{"msg": bson.M{"$each": msgListToMongo}}}).Err()
// if err != nil {
// log.Error(operationID, "FindOneAndUpdate failed ", err.Error(), filter)
// return utils.Wrap(err, "")
// }
// }
// if seqUidNext != "" {
// filter := bson.M{"uid": seqUidNext}
// sChat := UserChat{}
// sChat.UID = seqUidNext
// sChat.Msg = msgListToMongoNext
// log.NewDebug(operationID, "filter ", seqUidNext, "list ", msgListToMongoNext)
// if _, err = c.InsertOne(ctx, &sChat); err != nil {
// log.NewError(operationID, "InsertOne failed", filter, err.Error(), sChat)
// return utils.Wrap(err, "")
// }
// }
// log.NewWarn(operationID, "batch mgo cost time ", getCurrentTimestampByMill()-newTime, userID, len(msgList))
// return utils.Wrap(d.SetUserMaxSeq(userID, uint64(currentMaxSeq)), "")
//}
//func (d *DataBases)setMessageToCache(msgList []*pbMsg.MsgDataToMQ, uid string) (err error) {
//
//}
+12 -27
View File
@@ -61,21 +61,9 @@ func (m *Mongo) GetClient() *mongo.Client {
return m.db
}
func (m *Mongo) CreateTagIndex() {
if err := m.createMongoIndex(unrelation.CSendLog, false, "send_id", "-send_time"); err != nil {
panic(err.Error() + " index create failed " + unrelation.CSendLog + " send_id, -send_time")
}
if err := m.createMongoIndex(unrelation.CTag, false, "user_id", "-create_time"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CTag + " user_id, -create_time")
}
if err := m.createMongoIndex(unrelation.CTag, true, "tag_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CTag + " tag_id")
}
}
func (m *Mongo) CreateMsgIndex() {
if err := m.createMongoIndex(cChat, false, "uid"); err != nil {
fmt.Println(err.Error() + " index create failed " + cChat + " uid, please create index by yourself in field uid")
if err := m.createMongoIndex(unrelation, false, "uid"); err != nil {
fmt.Println(err.Error() + " index create failed " + unrelation.CChat + " uid, please create index by yourself in field uid")
}
}
@@ -88,21 +76,9 @@ func (m *Mongo) CreateSuperGroupIndex() {
}
}
func (m *Mongo) CreateWorkMomentIndex() {
if err := m.createMongoIndex(unrelation.CWorkMoment, true, "-create_time", "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " -create_time, work_moment_id")
}
if err := m.createMongoIndex(unrelation.CWorkMoment, true, "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " work_moment_id ")
}
if err := m.createMongoIndex(unrelation.CWorkMoment, false, "user_id", "-create_time"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + "user_id, -create_time")
}
}
func (m *Mongo) CreateExtendMsgSetIndex() {
if err := m.createMongoIndex(unrelation.CExtendMsgSet, true, "-create_time", "work_moment_id"); err != nil {
panic(err.Error() + "index create failed " + unrelation.CWorkMoment + " -create_time, work_moment_id")
panic(err.Error() + "index create failed " + unrelation.CExtendMsgSet + " -create_time, work_moment_id")
}
}
@@ -150,3 +126,12 @@ func MongoTransaction(ctx context.Context, mgo *mongo.Client, fn func(ctx mongo.
}
return utils.Wrap(sess.CommitTransaction(sCtx), "")
}
func getTxCtx(ctx context.Context, tx []any) context.Context {
if len(tx) > 0 {
if ctx, ok := tx[0].(mongo.SessionContext); ok {
return ctx
}
}
return ctx
}
+20 -26
View File
@@ -69,7 +69,7 @@ package unrelation
// return nil
//}
//func (d *db.DataBases) ReplaceMsgByIndex(suffixUserID string, msg *open_im_sdk.MsgData, operationID string, seqIndex int) error {
//func (d *db.DataBases) ReplaceMsgByIndex(suffixUserID string, msg *sdkws.MsgData, operationID string, seqIndex int) error {
// log.NewInfo(operationID, utils.GetSelfFuncName(), suffixUserID, *msg)
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@@ -90,7 +90,7 @@ package unrelation
// return nil
//}
//func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
//func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *sdkws.MsgData, operationID string) error {
// log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@@ -122,7 +122,7 @@ package unrelation
// return err
//}
//
//func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// log.NewInfo(operationID, utils.GetSelfFuncName(), uid, seqList)
// var hasSeqList []uint32
// singleCount := 0
@@ -153,7 +153,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
// return nil, err
@@ -217,11 +217,11 @@ package unrelation
// }
// for i, msg := range userChat.Msg {
// if i <= index {
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// if err = proto.Unmarshal(msg.Msg, msgPb); err != nil {
// continue
// }
// newMsgPb := &open_im_sdk.MsgData{Seq: msgPb.Seq}
// newMsgPb := &sdkws.MsgData{Seq: msgPb.Seq}
// bytes, err := proto.Marshal(newMsgPb)
// if err != nil {
// continue
@@ -235,7 +235,7 @@ package unrelation
// return replaceMaxSeq, err
//}
//
//func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetNewestMsg(ID string) (msg *sdkws.MsgData, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// regex := fmt.Sprintf("^%s", ID)
@@ -251,7 +251,7 @@ package unrelation
// }
// if len(userChats) > 0 {
// if len(userChats[0].Msg) > 0 {
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// err = proto.Unmarshal(userChats[0].Msg[len(userChats[0].Msg)-1].Msg, msgPb)
// if err != nil {
// return nil, utils.Wrap(err, "")
@@ -263,7 +263,7 @@ package unrelation
// return nil, nil
//}
//
//func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetOldestMsg(ID string) (msg *sdkws.MsgData, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// regex := fmt.Sprintf("^%s", ID)
@@ -288,7 +288,7 @@ package unrelation
// if len(oldestMsg) == 0 {
// oldestMsg = userChats[0].Msg[len(userChats[0].Msg)-1].Msg
// }
// msgPb := &open_im_sdk.MsgData{}
// msgPb := &sdkws.MsgData{}
// err = proto.Unmarshal(oldestMsg, msgPb)
// if err != nil {
// return nil, utils.Wrap(err, "")
@@ -298,7 +298,7 @@ package unrelation
// return nil, nil
//}
//
//func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// var hasSeqList []uint32
// singleCount := 0
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -325,7 +325,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
// return nil, err
@@ -349,7 +349,7 @@ package unrelation
// }
// return seqMsg, nil
//}
//func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
//func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
// var hasSeqList []uint32
// singleCount := 0
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -376,7 +376,7 @@ package unrelation
// }
// singleCount = 0
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", seqUid, value, groupID, seqList, err.Error())
// return nil, err
@@ -401,7 +401,7 @@ package unrelation
// return seqMsg, nil
//}
//
//func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, indexList []int, unexistSeqList []uint32, err error) {
//func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, indexList []int, unexistSeqList []uint32, err error) {
// ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
// c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
// sChat := UserChat{}
@@ -412,7 +412,7 @@ package unrelation
// singleCount := 0
// var hasSeqList []uint32
// for i := 0; i < len(sChat.Msg); i++ {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
// log.NewError(operationID, "Unmarshal err", msg.String(), err.Error())
// return nil, nil, nil, err
@@ -436,18 +436,18 @@ package unrelation
// return seqMsg, indexList, unexistSeqList, nil
//}
//
//func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
//func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*sdkws.MsgData) {
// for _, v := range seqList {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// msg.Seq = v
// exceptionMsg = append(exceptionMsg, msg)
// }
// return exceptionMsg
//}
//
//func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*open_im_sdk.MsgData) {
//func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*sdkws.MsgData) {
// for _, v := range seqList {
// msg := new(open_im_sdk.MsgData)
// msg := new(sdkws.MsgData)
// msg.Seq = v
// msg.GroupID = groupID
// msg.SessionType = constant.SuperGroupChatType
@@ -598,13 +598,7 @@ package unrelation
// return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func generateWorkMomentID(userID string) string {
// return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func generateWorkMomentCommentID(workMomentID string) string {
// return utils.Md5(workMomentID + strconv.Itoa(rand.Int()) + time.Now().String())
//}
//func getCurrentTimestampByMill() int64 {
// return time.Now().UnixNano() / 1e6
+36 -21
View File
@@ -27,6 +27,16 @@ func NewMsgMongoDriver(mgoDB *mongo.Database) *MsgMongoDriver {
return &MsgMongoDriver{mgoDB: mgoDB, MsgCollection: mgoDB.Collection(unrelation.CChat)}
}
func (m *MsgMongoDriver) FindOneAndUpdate(ctx context.Context, filter, update, output interface{}, opts ...*options.FindOneAndUpdateOptions) error {
return m.MsgCollection.FindOneAndUpdate(ctx, filter, update, opts...).Decode(output)
}
func (m *MsgMongoDriver) UpdateOne(ctx context.Context, filter, update interface{}, opts ...*options.UpdateOptions) error {
_, err := m.MsgCollection.UpdateOne(ctx, filter, update, opts...)
return err
}
// database controller
func (m *MsgMongoDriver) DelMsgBySeqList(ctx context.Context, userID string, seqList []uint32) (totalUnExistSeqList []uint32, err error) {
sortkeys.Uint32s(seqList)
suffixUserID2SubSeqList := func(uid string, seqList []uint32) map[string][]uint32 {
@@ -73,6 +83,7 @@ func (m *MsgMongoDriver) DelMsgBySeqListInOneDoc(ctx context.Context, suffixUser
return unexistSeqList, nil
}
// database
func (m *MsgMongoDriver) DelMsgLogic(ctx context.Context, uid string, seqList []uint32) error {
sortkeys.Uint32s(seqList)
seqMsgs, err := d.GetMsgBySeqListMongo2(ctx, uid, seqList)
@@ -88,6 +99,7 @@ func (m *MsgMongoDriver) DelMsgLogic(ctx context.Context, uid string, seqList []
return nil
}
// model
func (m *MsgMongoDriver) ReplaceMsgByIndex(ctx context.Context, suffixUserID string, msg *sdkws.MsgData, seqIndex int) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), suffixUserID, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -109,7 +121,7 @@ func (m *MsgMongoDriver) ReplaceMsgByIndex(ctx context.Context, suffixUserID str
return nil
}
func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *open_im_sdk.MsgData, operationID string) error {
func (d *db.DataBases) ReplaceMsgBySeq(uid string, msg *sdkws.MsgData, operationID string) error {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, *msg)
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@@ -141,7 +153,7 @@ func (d *db.DataBases) UpdateOneMsgList(msg *UserChat) error {
return err
}
func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
log.NewInfo(operationID, utils.GetSelfFuncName(), uid, seqList)
var hasSeqList []uint32
singleCount := 0
@@ -172,7 +184,7 @@ func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
@@ -197,10 +209,11 @@ func (d *db.DataBases) GetMsgBySeqList(uid string, seqList []uint32, operationID
return seqMsg, nil
}
func (d *db.DataBases) GetUserMsgListByIndex(ID string, index int64) (*UserChat, error) {
// model
func (d *db.DataBases) GetUserMsgListByIndex(docID string, index int64) (*UserChat, error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
regex := fmt.Sprintf("^%s", docID)
findOpts := options.Find().SetLimit(1).SetSkip(index).SetSort(bson.M{"uid": 1})
var msgs []UserChat
//primitive.Regex{Pattern: regex}
@@ -219,6 +232,7 @@ func (d *db.DataBases) GetUserMsgListByIndex(ID string, index int64) (*UserChat,
}
}
// model
func (d *db.DataBases) DelMongoMsgs(IDList []string) error {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@@ -226,6 +240,7 @@ func (d *db.DataBases) DelMongoMsgs(IDList []string) error {
return err
}
// model
func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (replaceMaxSeq uint32, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
@@ -236,11 +251,11 @@ func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (rep
}
for i, msg := range userChat.Msg {
if i <= index {
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
if err = proto.Unmarshal(msg.Msg, msgPb); err != nil {
continue
}
newMsgPb := &open_im_sdk.MsgData{Seq: msgPb.Seq}
newMsgPb := &sdkws.MsgData{Seq: msgPb.Seq}
bytes, err := proto.Marshal(newMsgPb)
if err != nil {
continue
@@ -254,7 +269,7 @@ func (d *db.DataBases) ReplaceMsgToBlankByIndex(suffixID string, index int) (rep
return replaceMaxSeq, err
}
func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetNewestMsg(ID string) (msg *sdkws.MsgData, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
@@ -270,7 +285,7 @@ func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err er
}
if len(userChats) > 0 {
if len(userChats[0].Msg) > 0 {
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
err = proto.Unmarshal(userChats[0].Msg[len(userChats[0].Msg)-1].Msg, msgPb)
if err != nil {
return nil, utils.Wrap(err, "")
@@ -282,7 +297,7 @@ func (d *db.DataBases) GetNewestMsg(ID string) (msg *open_im_sdk.MsgData, err er
return nil, nil
}
func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetOldestMsg(ID string) (msg *sdkws.MsgData, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
regex := fmt.Sprintf("^%s", ID)
@@ -307,7 +322,7 @@ func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err er
if len(oldestMsg) == 0 {
oldestMsg = userChats[0].Msg[len(userChats[0].Msg)-1].Msg
}
msgPb := &open_im_sdk.MsgData{}
msgPb := &sdkws.MsgData{}
err = proto.Unmarshal(oldestMsg, msgPb)
if err != nil {
return nil, utils.Wrap(err, "")
@@ -317,7 +332,7 @@ func (d *db.DataBases) GetOldestMsg(ID string) (msg *open_im_sdk.MsgData, err er
return nil, nil
}
func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
var hasSeqList []uint32
singleCount := 0
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -344,7 +359,7 @@ func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, opera
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, uid, seqList, err.Error())
return nil, err
@@ -368,7 +383,7 @@ func (d *db.DataBases) GetMsgBySeqListMongo2(uid string, seqList []uint32, opera
}
return seqMsg, nil
}
func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, err error) {
func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, err error) {
var hasSeqList []uint32
singleCount := 0
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
@@ -395,7 +410,7 @@ func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []
}
singleCount = 0
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", seqUid, value, groupID, seqList, err.Error())
return nil, err
@@ -420,7 +435,7 @@ func (d *db.DataBases) GetSuperGroupMsgBySeqListMongo(groupID string, seqList []
return seqMsg, nil
}
func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*open_im_sdk.MsgData, indexList []int, unexistSeqList []uint32, err error) {
func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, seqList []uint32, operationID string) (seqMsg []*sdkws.MsgData, indexList []int, unexistSeqList []uint32, err error) {
ctx, _ := context.WithTimeout(context.Background(), time.Duration(config.Config.Mongo.DBTimeout)*time.Second)
c := d.mongoClient.Database(config.Config.Mongo.DBDatabase).Collection(cChat)
sChat := UserChat{}
@@ -431,7 +446,7 @@ func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, s
singleCount := 0
var hasSeqList []uint32
for i := 0; i < len(sChat.Msg); i++ {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
if err = proto.Unmarshal(sChat.Msg[i].Msg, msg); err != nil {
log.NewError(operationID, "Unmarshal err", msg.String(), err.Error())
return nil, nil, nil, err
@@ -455,18 +470,18 @@ func (d *db.DataBases) GetMsgAndIndexBySeqListInOneMongo2(suffixUserID string, s
return seqMsg, indexList, unexistSeqList, nil
}
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*open_im_sdk.MsgData) {
func genExceptionMessageBySeqList(seqList []uint32) (exceptionMsg []*sdkws.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
msg.Seq = v
exceptionMsg = append(exceptionMsg, msg)
}
return exceptionMsg
}
func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*open_im_sdk.MsgData) {
func genExceptionSuperGroupMessageBySeqList(seqList []uint32, groupID string) (exceptionMsg []*sdkws.MsgData) {
for _, v := range seqList {
msg := new(open_im_sdk.MsgData)
msg := new(sdkws.MsgData)
msg.Seq = v
msg.GroupID = groupID
msg.SessionType = constant.SuperGroupChatType
-9
View File
@@ -111,15 +111,6 @@ type SuperGroupMongoDriver struct {
// panic("implement me")
// }
func (s *SuperGroupMongoDriver) getTxCtx(ctx context.Context, tx []any) context.Context {
if len(tx) > 0 {
if ctx, ok := tx[0].(mongo.SessionContext); ok {
return ctx
}
}
return ctx
}
//func (s *SuperGroupMongoDriver) Transaction(ctx context.Context, fn func(ctx mongo.SessionContext) error) error {
// sess, err := s.MgoClient.StartSession()
// if err != nil {
-117
View File
@@ -1,117 +0,0 @@
package unrelation
import (
"Open_IM/pkg/common/db/table/unrelation"
"Open_IM/pkg/utils"
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
"strconv"
"time"
)
type TagMongoDriver struct {
mgoDB *mongo.Database
TagCollection *mongo.Collection
TagSendLogCollection *mongo.Collection
}
func NewTagMongoDriver(mgoDB *mongo.Database) *TagMongoDriver {
return &TagMongoDriver{mgoDB: mgoDB, TagCollection: mgoDB.Collection(unrelation.CTag), TagSendLogCollection: mgoDB.Collection(unrelation.CSendLog)}
}
func (db *TagMongoDriver) generateTagID(tagName, userID string) string {
return utils.Md5(tagName + userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *TagMongoDriver) GetUserTags(ctx context.Context, userID string) ([]unrelation.TagModel, error) {
var tags []unrelation.TagModel
cursor, err := db.TagCollection.Find(ctx, bson.M{"user_id": userID})
if err != nil {
return tags, err
}
if err = cursor.All(ctx, &tags); err != nil {
return tags, err
}
return tags, nil
}
func (db *TagMongoDriver) CreateTag(ctx context.Context, userID, tagName string, userList []string) error {
tagID := generateTagID(tagName, userID)
tag := unrelation.TagModel{
UserID: userID,
TagID: tagID,
TagName: tagName,
UserList: userList,
}
_, err := db.TagCollection.InsertOne(ctx, tag)
return err
}
func (db *TagMongoDriver) GetTagByID(ctx context.Context, userID, tagID string) (unrelation.TagModel, error) {
var tag unrelation.TagModel
err := db.TagCollection.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag, err
}
func (db *TagMongoDriver) DeleteTag(ctx context.Context, userID, tagID string) error {
_, err := db.TagCollection.DeleteOne(ctx, bson.M{"user_id": userID, "tag_id": tagID})
return err
}
func (db *TagMongoDriver) SetTag(ctx context.Context, userID, tagID, newName string, increaseUserIDList []string, reduceUserIDList []string) error {
var tag unrelation.TagModel
if err := db.TagCollection.FindOne(ctx, bson.M{"tag_id": tagID, "user_id": userID}).Decode(&tag); err != nil {
return err
}
if newName != "" {
_, err := db.TagCollection.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"tag_name": newName}})
if err != nil {
return err
}
}
tag.UserList = append(tag.UserList, increaseUserIDList...)
tag.UserList = utils.RemoveRepeatedStringInList(tag.UserList)
for _, v := range reduceUserIDList {
for i2, v2 := range tag.UserList {
if v == v2 {
tag.UserList[i2] = ""
}
}
}
var newUserList []string
for _, v := range tag.UserList {
if v != "" {
newUserList = append(newUserList, v)
}
}
_, err := db.TagCollection.UpdateOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}, bson.M{"$set": bson.M{"user_list": newUserList}})
if err != nil {
return err
}
return nil
}
func (db *TagMongoDriver) GetUserIDListByTagID(ctx context.Context, userID, tagID string) ([]string, error) {
var tag unrelation.TagModel
err := db.TagCollection.FindOne(ctx, bson.M{"user_id": userID, "tag_id": tagID}).Decode(&tag)
return tag.UserList, err
}
func (db *TagMongoDriver) SaveTagSendLog(ctx context.Context, tagSendLog *unrelation.TagSendLogModel) error {
_, err := db.TagSendLogCollection.InsertOne(ctx, tagSendLog)
return err
}
func (db *TagMongoDriver) GetTagSendLogs(ctx context.Context, userID string, showNumber, pageNumber int32) ([]unrelation.TagSendLogModel, error) {
var tagSendLogs []unrelation.TagSendLogModel
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"send_time": -1})
cursor, err := db.TagSendLogCollection.Find(ctx, bson.M{"send_id": userID}, findOpts)
if err != nil {
return tagSendLogs, err
}
err = cursor.All(ctx, &tagSendLogs)
return tagSendLogs, err
}
-151
View File
@@ -1,151 +0,0 @@
package unrelation
import (
"Open_IM/pkg/common/config"
"Open_IM/pkg/common/constant"
"Open_IM/pkg/common/db/table/unrelation"
"Open_IM/pkg/utils"
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"math/rand"
"strconv"
"time"
)
type WorkMomentMongoDriver struct {
mgoDB *mongo.Database
WorkMomentCollection *mongo.Collection
}
func NewWorkMomentMongoDriver(mgoDB *mongo.Database) *WorkMomentMongoDriver {
return &WorkMomentMongoDriver{mgoDB: mgoDB, WorkMomentCollection: mgoDB.Collection(unrelation.CWorkMoment)}
}
func (db *WorkMomentMongoDriver) generateWorkMomentID(userID string) string {
return utils.Md5(userID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *WorkMomentMongoDriver) generateWorkMomentCommentID(workMomentID string) string {
return utils.Md5(workMomentID + strconv.Itoa(rand.Int()) + time.Now().String())
}
func (db *WorkMomentMongoDriver) CreateOneWorkMoment(ctx context.Context, workMoment *unrelation.WorkMoment) error {
workMomentID := db.generateWorkMomentID(workMoment.UserID)
workMoment.WorkMomentID = workMomentID
workMoment.CreateTime = int32(time.Now().Unix())
_, err := db.WorkMomentCollection.InsertOne(ctx, workMoment)
return err
}
func (db *WorkMomentMongoDriver) DeleteOneWorkMoment(ctx context.Context, workMomentID string) error {
_, err := db.WorkMomentCollection.DeleteOne(ctx, bson.M{"work_moment_id": workMomentID})
return err
}
func (db *WorkMomentMongoDriver) DeleteComment(ctx context.Context, workMomentID, contentID, opUserID string) error {
_, err := db.WorkMomentCollection.UpdateOne(ctx, bson.D{{"work_moment_id", workMomentID},
{"$or", bson.A{
bson.D{{"user_id", opUserID}},
bson.D{{"comments", bson.M{"$elemMatch": bson.M{"user_id": opUserID}}}},
},
}}, bson.M{"$pull": bson.M{"comments": bson.M{"content_id": contentID}}})
return err
}
func (db *WorkMomentMongoDriver) GetWorkMomentByID(ctx context.Context, workMomentID string) (*unrelation.WorkMoment, error) {
workMoment := &unrelation.WorkMoment{}
err := db.WorkMomentCollection.FindOne(ctx, bson.M{"work_moment_id": workMomentID}).Decode(workMoment)
return workMoment, err
}
func (db *WorkMomentMongoDriver) LikeOneWorkMoment(ctx context.Context, likeUserID, userName, workMomentID string) (*unrelation.WorkMoment, bool, error) {
workMoment, err := db.GetWorkMomentByID(ctx, workMomentID)
if err != nil {
return nil, false, err
}
var isAlreadyLike bool
for i, user := range workMoment.LikeUserList {
if likeUserID == user.UserID {
isAlreadyLike = true
workMoment.LikeUserList = append(workMoment.LikeUserList[0:i], workMoment.LikeUserList[i+1:]...)
}
}
if !isAlreadyLike {
workMoment.LikeUserList = append(workMoment.LikeUserList, &unrelation.CommonUserModel{UserID: likeUserID, UserName: userName})
}
_, err = db.WorkMomentCollection.UpdateOne(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$set": bson.M{"like_user_list": workMoment.LikeUserList}})
return workMoment, !isAlreadyLike, err
}
func (db *WorkMomentMongoDriver) CommentOneWorkMoment(ctx context.Context, comment *unrelation.Comment, workMomentID string) (unrelation.WorkMoment, error) {
comment.ContentID = generateWorkMomentCommentID(workMomentID)
var workMoment unrelation.WorkMoment
err := db.WorkMomentCollection.FindOneAndUpdate(ctx, bson.M{"work_moment_id": workMomentID}, bson.M{"$push": bson.M{"comments": comment}}).Decode(&workMoment)
return workMoment, err
}
func (db *WorkMomentMongoDriver) GetUserSelfWorkMoments(ctx context.Context, userID string, showNumber, pageNumber int32) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := db.WorkMomentCollection.Find(ctx, bson.M{"user_id": userID}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (db *WorkMomentMongoDriver) GetUserWorkMoments(ctx context.Context, opUserID, userID string, showNumber, pageNumber int32, friendIDList []string) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
result, err := db.WorkMomentCollection.Find(ctx, bson.D{ // 等价条件: select * from
{"user_id", userID},
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{opUserID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{opUserID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}},
}, findOpts)
if err != nil {
return workMomentList, nil
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}
func (db *WorkMomentMongoDriver) GetUserFriendWorkMoments(ctx context.Context, showNumber, pageNumber int32, userID string, friendIDList []string) ([]unrelation.WorkMoment, error) {
var workMomentList []unrelation.WorkMoment
findOpts := options.Find().SetLimit(int64(showNumber)).SetSkip(int64(showNumber) * (int64(pageNumber) - 1)).SetSort(bson.M{"create_time": -1})
var filter bson.D
permissionFilter := bson.D{
{"$or", bson.A{
bson.D{{"permission", constant.WorkMomentPermissionCantSee}, {"permission_user_id_list", bson.D{{"$nin", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPermissionCanSee}, {"permission_user_id_list", bson.D{{"$in", bson.A{userID}}}}},
bson.D{{"permission", constant.WorkMomentPublic}},
}}}
if config.Config.WorkMoment.OnlyFriendCanSee {
filter = bson.D{
{"$or", bson.A{
bson.D{{"user_id", userID}}, //self
bson.D{{"$and", bson.A{permissionFilter, bson.D{{"user_id", bson.D{{"$in", friendIDList}}}}}}},
},
},
}
} else {
filter = bson.D{
{"$or", bson.A{
bson.D{{"user_id", userID}}, //self
permissionFilter,
},
},
}
}
result, err := db.WorkMomentCollection.Find(ctx, filter, findOpts)
if err != nil {
return workMomentList, err
}
err = result.All(ctx, &workMomentList)
return workMomentList, err
}