Skip to content

Commit

Permalink
1. 增加 /api/v1/chat/message/last 接口
Browse files Browse the repository at this point in the history
2. 修改workflows文件,增加触发docs自动编译
  • Loading branch information
jerbe committed Sep 8, 2023
1 parent a9742c5 commit a4edf4f
Show file tree
Hide file tree
Showing 14 changed files with 386 additions and 323 deletions.
10 changes: 9 additions & 1 deletion .github/workflows/cross-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ jobs:
bin_arrays=($(ls jim-*))
for ((i=0; i<${#bin_arrays[@]}; i++)); do
zip_name=$(echo ${bin_arrays[$i]}|awk -F '-' '{print $2"-"$3}'|awk -F'.' '{print $1}')
zip -r ${zip_name}.zip ./${bin_arrays[$i]} ./config/ ./sql/
zip -r ${zip_name}-${{ github.event.inputs.version}}.zip ./${bin_arrays[$i]} ./config/ ./sql/
done
echo "status=success" >> $GITHUB_OUTPUT
Expand Down Expand Up @@ -124,6 +124,14 @@ jobs:
git push "https://${{ secrets.ACCESS_TOKEN }}@github.com/jerbe/jim-docs.git" HEAD:main
echo "推送标签(tag)"
git push --force origin ${{ github.event.inputs.version }}
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.ACCESS_TOKEN }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/jerbe/jim-docs/actions/workflows/build.yml/dispatches \
-d '{"ref":"main","inputs":{"version":"${{ github.event.inputs.version }} "}}'
else
echo "没有东西需要提交"
exit 0
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ Here are the planned features:
### Chat
- [ ] Chat List
- [ ] Pin chats
- [ ] Last message in chat list
- [x] Last message in chat room
- [x] Private Chat
- [x] Send plain text
- [ ] Send images
Expand Down
2 changes: 1 addition & 1 deletion README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ JIM 是一个轻量的聊天系统,
### 聊天
- [ ] 聊天列表
- [ ] 置顶聊天
- [ ] 聊天列表最后一条消息
- [x] 聊天房间的最后消息
- [x] 私聊
- [x] 纯文本聊天
- [ ] 发送图片
Expand Down
80 changes: 46 additions & 34 deletions database/chat.go
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ type ChatMessage struct {
SessionType int `bson:"session_type" json:"session_type"`

// 发送人ID
SenderID int64 `bson:"sender_id"`
SenderID int64 `bson:"sender_id" json:"sender_id"`

// 接收人ID
ReceiverID int64 `bson:"receiver_id"`
ReceiverID int64 `bson:"receiver_id" json:"receiver_id"`

// 消息发送状态,1-已发送,2-未抵达,3-已抵达
SendStatus int `bson:"send_status" json:"send_status"`
Expand Down Expand Up @@ -278,10 +278,10 @@ func AddChatMessage(msg *ChatMessage) error {
err = jcache.Push(GlobCtx, cacheKey, msg)
if err != nil && err.Error() == "WRONGTYPE Operation against a key holding the wrong kind of value" {
jcache.Del(GlobCtx, cacheKey)
err = jcache.Push(GlobCtx, cacheKey, msg)
if err != nil {
log.Warn().Err(err).Msg("缓存插入聊天消息失败")
}
}

if err == nil {
jcache.Expire(GlobCtx, cacheKey, jcache.RandomExpirationDuration())
}

return nil
Expand Down Expand Up @@ -326,12 +326,6 @@ func AddChatMessageTx(msg *ChatMessage) error {
return nil, errors.Wrap(err)
}

// 将聊天数据推送到缓存定长队列中去
err = jcache.Push(GlobCtx, cacheKeyFormatLastMessageList(msg.RoomID, msg.SessionType), msg)
if err != nil {
log.Error().Err(err).Msgf("推送消息到缓存列表失败:\n %+v", err)
}

// 更新聊天室的最后一条消息
_, err = db.Collection(CollectionRoom).
UpdateOne(ctxb, bson.M{
Expand All @@ -344,6 +338,18 @@ func AddChatMessageTx(msg *ChatMessage) error {
if err != nil {
return nil, errors.Wrap(err)
}

// 将聊天数据推送到缓存定长队列中去
cacheKey := cacheKeyFormatLastMessageList(msg.RoomID, msg.SessionType)
err = jcache.Push(GlobCtx, cacheKey, msg)
if err != nil {
jcache.Del(GlobCtx, cacheKey)
log.Error().Err(err).Msgf("推送消息到缓存列表失败:\n %+v", err)
}
if err == nil {
jcache.Expire(GlobCtx, cacheKey, jcache.RandomExpirationDuration())
}

return nil, nil
}, options.Transaction().SetWriteConcern(writeconcern.Majority()).SetReadConcern(readconcern.Snapshot()))
if err != nil {
Expand Down Expand Up @@ -416,38 +422,40 @@ func NewChatMessageListOptions() *GetChatMessageListOptions {
}
}

type GetChatMessageListFilter struct {
RoomID string `bson:"room_id"`
SessionType int `bson:"session_type"`
Sort any `bson:"sort"`
LastMessageID *int64 `bson:"last_message_id"`
Limit *int `bson:"limit"`
}

// GetChatMessageList 获取消息列表
func GetChatMessageList(roomID string, sessionType int, opts ...*GetChatMessageListOptions) ([]*ChatMessage, error) {
opt := NewChatMessageListOptions()
func GetChatMessageList(filter *GetChatMessageListFilter, opts ...*GetOptions) ([]*ChatMessage, error) {
if filter.Sort == nil {
filter.Sort = bson.M{"message_id": -1}
}

for _, o := range opts {
if opt.Sort == nil && o.Sort != nil {
opt.Sort = o.Sort
}
if o.LastMessageID > opt.LastMessageID {
opt.LastMessageID = o.LastMessageID
}
if o.Limit > opt.Limit {
opt.Limit = o.Limit
if filter.LastMessageID == nil {
filter.LastMessageID = new(int64)
}

if opt.Limit > defaultMaxLimit {
opt.Limit = defaultMaxLimit
}
}
if filter.Limit == nil {
filter.Limit = new(int)
}

rs, err := GlobDB.Mongo.Database(DatabaseMongodbIM).
Collection(CollectionMessage).
Find(GlobCtx, bson.M{
"room_id": roomID,
"session_type": sessionType,
"room_id": filter.RoomID,
"session_type": filter.SessionType,
"message_id": bson.M{
"$gte": opt.LastMessageID,
"$lt": opt.LastMessageID + opt.Limit,
"$gte": *filter.LastMessageID,
"$lt": (*filter.LastMessageID) + int64(*filter.Limit),
},
}, options.Find().SetSort(opt.Sort))
}, options.Find().SetSort(filter.Sort))
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.IsNoRecord(err) {
return nil, errors.Wrap(err)
}
return nil, errors.Wrap(err)
Expand All @@ -469,6 +477,7 @@ func GetChatMessageList(roomID string, sessionType int, opts ...*GetChatMessageL
func GetLastChatMessageList(roomID string, sessionType int, opts ...*GetOptions) ([]*ChatMessage, error) {
opt := MergeGetOptions(opts)
cacheKey := cacheKeyFormatLastMessageList(roomID, sessionType)

// 如果有使用缓存,则从缓存中获取
if opt.UseCache() {
exists, _ := jcache.Exists(GlobCtx, cacheKey)
Expand All @@ -491,7 +500,7 @@ func GetLastChatMessageList(roomID string, sessionType int, opts ...*GetOptions)
Find(GlobCtx, bson.M{
"room_id": roomID,
"session_type": sessionType,
}, options.Find().SetSort(bson.M{"created_at": -1}).SetLimit(defaultLastLimit))
}, options.Find().SetSort(bson.M{"message_id": -1}).SetLimit(defaultLastLimit))

if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
Expand Down Expand Up @@ -528,6 +537,9 @@ func GetLastChatMessageList(roomID string, sessionType int, opts ...*GetOptions)
log.Warn().Err(err).Msg("缓存插入聊天消息失败")
}
}
if err == nil {
jcache.Expire(GlobCtx, cacheKey, jcache.RandomExpirationDuration())
}

// 设置缓存
return messages, nil
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ require (
github.com/go-playground/validator/v10 v10.15.3 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/uuid v1.3.1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jerbe/jcache v1.0.0 h1:xi2ErWRAZQTB5hHTcB0nF8kdvx4ZQ/4SJrhmDsIEStM=
Expand Down
Loading

0 comments on commit a4edf4f

Please sign in to comment.