/
api_conversation.go
1091 lines (1003 loc) · 38.3 KB
/
api_conversation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package message
import (
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"github.com/TangSengDaoDao/TangSengDaoDaoServer/modules/base/event"
"github.com/TangSengDaoDao/TangSengDaoDaoServer/modules/channel"
chservice "github.com/TangSengDaoDao/TangSengDaoDaoServer/modules/channel/service"
"github.com/TangSengDaoDao/TangSengDaoDaoServer/modules/group"
"github.com/TangSengDaoDao/TangSengDaoDaoServer/modules/user"
"github.com/TangSengDaoDao/TangSengDaoDaoServerLib/common"
"github.com/TangSengDaoDao/TangSengDaoDaoServerLib/config"
"github.com/TangSengDaoDao/TangSengDaoDaoServerLib/pkg/log"
"github.com/TangSengDaoDao/TangSengDaoDaoServerLib/pkg/util"
"github.com/TangSengDaoDao/TangSengDaoDaoServerLib/pkg/wkhttp"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// Conversation 最近会话
type Conversation struct {
ctx *config.Context
log.Log
userDB *user.DB
groupDB *group.DB
messageExtraDB *messageExtraDB
messageReactionDB *messageReactionDB
messageUserExtraDB *messageUserExtraDB
channelOffsetDB *channelOffsetDB
deviceOffsetDB *deviceOffsetDB
userLastOffsetDB *userLastOffsetDB
userService user.IService
groupService group.IService
service IService
channelService chservice.IService
conversationExtraDB *conversationExtraDB
syncConversationResultCacheMap map[string][]string
syncConversationVersionMap map[string]int64
syncConversationResultCacheLock sync.RWMutex
}
// New New
func NewConversation(ctx *config.Context) *Conversation {
return &Conversation{
ctx: ctx,
Log: log.NewTLog("Coversation"),
userDB: user.NewDB(ctx),
groupDB: group.NewDB(ctx),
messageExtraDB: newMessageExtraDB(ctx),
messageUserExtraDB: newMessageUserExtraDB(ctx),
messageReactionDB: newMessageReactionDB(ctx),
channelOffsetDB: newChannelOffsetDB(ctx),
deviceOffsetDB: newDeviceOffsetDB(ctx.DB()),
userLastOffsetDB: newUserLastOffsetDB(ctx),
conversationExtraDB: newConversationExtraDB(ctx),
userService: user.NewService(ctx),
groupService: group.NewService(ctx),
channelService: channel.NewService(ctx),
service: NewService(ctx),
syncConversationResultCacheMap: map[string][]string{},
syncConversationVersionMap: map[string]int64{},
}
}
// Route 路由配置
func (co *Conversation) Route(r *wkhttp.WKHttp) {
// TODO: 这个里的接口后面移到 conversation的组里,因为单词拼错了 😭
coversations := r.Group("/v1/coversations", co.ctx.AuthMiddleware(r))
{
// 获取最近会话 TODO: 此接口应该没有被使用了
coversations.GET("", co.getConversations)
}
// TODO: 这个里的接口后面移到 conversation的组里,因为单词拼错了 😭
cnversation := r.Group("/v1/coversation", co.ctx.AuthMiddleware(r))
{
cnversation.PUT("/clearUnread", co.clearConversationUnread)
}
conversation := r.Group("/v1/conversation", co.ctx.AuthMiddleware(r))
{
// 离线的最近会话
conversation.POST("/sync", co.syncUserConversation)
conversation.POST("/syncack", co.syncUserConversationAck)
conversation.POST("/extra/sync", co.conversationExtraSync) // 同步最近会话扩展
}
conversations := r.Group("/v1/conversations", co.ctx.AuthMiddleware(r))
{
conversations.DELETE("/:channel_id/:channel_type", co.deleteConversation) // 删除最近会话
conversations.POST("/:channel_id/:channel_type/extra", co.conversationExtraUpdate) // 添加或更新最近会话扩展
}
co.ctx.AddEventListener(event.ConversationDelete, func(data []byte, commit config.EventCommit) {
co.handleConversationDeleteEvent(data, commit)
})
}
func (co *Conversation) handleConversationDeleteEvent(data []byte, commit config.EventCommit) {
var req config.DeleteConversationReq
err := util.ReadJsonByByte([]byte(data), &req)
if err != nil {
co.Error("解析最近会话删除JSON失败!", zap.Error(err), zap.String("data", string(data)))
commit(err)
return
}
err = co.service.DeleteConversation(req.UID, req.ChannelID, req.ChannelType)
if err != nil {
co.Error("删除最近会话失败!", zap.Error(err))
commit(err)
return
}
commit(nil)
}
// 最近会话扩展同步
func (co *Conversation) conversationExtraSync(c *wkhttp.Context) {
var req struct {
Version int64 `json:"version"`
}
if err := c.BindJSON(&req); err != nil {
co.Error("数据格式有误!", zap.Error(err))
c.ResponseError(errors.New("数据格式有误!"))
return
}
loginUID := c.GetLoginUID()
conversationExtraModels, err := co.conversationExtraDB.sync(loginUID, req.Version)
if err != nil {
co.Error("同步消息扩展失败!", zap.Error(err))
c.ResponseError(errors.New("同步消息扩展失败!"))
return
}
resps := make([]*conversationExtraResp, 0, len(conversationExtraModels))
for _, conversationExtraM := range conversationExtraModels {
resps = append(resps, newConversationExtraResp(conversationExtraM))
}
c.JSON(http.StatusOK, resps)
}
// 更新最近会话扩展
func (co *Conversation) conversationExtraUpdate(c *wkhttp.Context) {
var req struct {
BrowseTo uint32 `json:"browse_to"` // 预览位置 预览到的位置,与会话保持位置不同的是 预览到的位置是用户读到的最大的messageSeq。跟未读消息数量有关系
KeepMessageSeq uint32 `json:"keep_message_seq"` // 保存位置的messageSeq
KeepOffsetY int `json:"keep_offset_y"` // Y的偏移量
Draft string `json:"draft"` // 草稿
}
if err := c.BindJSON(&req); err != nil {
co.Error("数据格式有误!", zap.Error(err))
c.ResponseError(errors.New("数据格式有误!"))
return
}
channelID := c.Param("channel_id")
channelTypeStr := c.Param("channel_type")
loginUID := c.GetLoginUID()
channelTypeI64, _ := strconv.ParseInt(channelTypeStr, 10, 64)
version := co.ctx.GenSeq(common.SyncConversationExtraKey)
err := co.conversationExtraDB.insertOrUpdate(&conversationExtraModel{
UID: loginUID,
ChannelID: channelID,
ChannelType: uint8(channelTypeI64),
BrowseTo: req.BrowseTo,
KeepMessageSeq: req.KeepMessageSeq,
KeepOffsetY: req.KeepOffsetY,
Draft: req.Draft,
Version: version,
})
if err != nil {
co.Error("添加或更新最近会话扩展失败!", zap.Error(err))
c.ResponseError(errors.New("添加或更新最近会话扩展失败!"))
return
}
err = co.ctx.SendCMD(config.MsgCMDReq{
NoPersist: true,
ChannelID: loginUID,
ChannelType: uint8(common.ChannelTypePerson),
CMD: common.CMDSyncConversationExtra,
})
if err != nil {
co.Error("发送同步扩展会话cmd失败!", zap.Error(err))
c.ResponseError(errors.New("发送同步扩展会话cmd失败!"))
return
}
c.JSON(http.StatusOK, gin.H{
"version": version,
})
}
// 删除最近会话
func (co *Conversation) deleteConversation(c *wkhttp.Context) {
channelID := c.Param("channel_id")
channelType, _ := strconv.ParseInt(c.Param("channel_type"), 10, 64)
err := co.service.DeleteConversation(c.GetLoginUID(), channelID, uint8(channelType))
if err != nil {
co.Error("删除最近会话失败!", zap.Error(err))
c.ResponseError(errors.New("删除最近会话失败!"))
return
}
c.ResponseOK()
}
// 获取离线的最近会话
func (co *Conversation) syncUserConversation(c *wkhttp.Context) {
var req struct {
Version int64 `json:"version"` // 当前客户端的会话最大版本号(客户端最新会话的时间戳)
LastMsgSeqs string `json:"last_msg_seqs"` // 客户端所有会话的最后一条消息序列号 格式: channelID:channelType:last_msg_seq|channelID:channelType:last_msg_seq
MsgCount int64 `json:"msg_count"` // 每个会话消息数量
DeviceUUID string `json:"device_uuid"` // 设备uuid
}
if err := c.BindJSON(&req); err != nil {
co.Error("数据格式有误!", zap.Error(err))
c.ResponseError(errors.New("数据格式有误!"))
return
}
version := req.Version
loginUID := c.GetLoginUID()
deviceOffsetModelMap := map[string]*deviceOffsetModel{}
lastMsgSeqs := req.LastMsgSeqs
if !co.ctx.GetConfig().MessageSaveAcrossDevice {
/**
1.获取设备的最大version 作为同步version
2. 如果设备最大version不存在 则把用户最大的version 作为设备version
**/
cacheVersion, err := co.getDeviceConversationMaxVersion(loginUID, req.DeviceUUID)
if err != nil {
co.Error("获取缓存的最近会话版本号失败!", zap.Error(err), zap.String("loginUID", loginUID), zap.String("deviceUUID", req.DeviceUUID))
c.ResponseError(errors.New("获取缓存的最近会话版本号失败!"))
return
}
if cacheVersion == 0 {
userMaxVersion, err := co.getUserConversationMaxVersion(loginUID)
if err != nil {
co.Error("获取用户最近会很最大版本失败!", zap.Error(err))
c.ResponseError(errors.New("获取用户最近会很最大版本失败!"))
return
}
if userMaxVersion > 0 {
err = co.setDeviceConversationMaxVersion(loginUID, req.DeviceUUID, userMaxVersion)
if err != nil {
co.Error("设置设备最近会话最大版本号失败!", zap.Error(err))
c.ResponseError(errors.New("设置设备最近会话最大版本号失败!"))
return
}
}
cacheVersion = userMaxVersion
}
if cacheVersion > version {
version = cacheVersion
}
// ---------- 设备消息偏移 ----------
if !co.ctx.GetConfig().MessageSaveAcrossDevice { // 以下为不开启夸设备存储的逻辑
lastMsgSeqList := make([]string, 0)
deviceOffsetModels, err := co.deviceOffsetDB.queryWithUIDAndDeviceUUID(loginUID, req.DeviceUUID)
if err != nil {
co.Error("查询用户设备偏移量失败!", zap.Error(err))
c.ResponseError(errors.New("查询用户设备偏移量失败!"))
return
}
if len(deviceOffsetModels) > 0 {
for _, deviceOffsetM := range deviceOffsetModels {
deviceOffsetModelMap[fmt.Sprintf("%s-%d", deviceOffsetM.ChannelID, deviceOffsetM.ChannelType)] = deviceOffsetM
lastMsgSeqList = append(lastMsgSeqList, fmt.Sprintf("%s:%d:%d", deviceOffsetM.ChannelID, deviceOffsetM.ChannelType, deviceOffsetM.MessageSeq))
}
} else { // 如果没有设备的偏移量 则取用户最新的偏移量作为设备偏移量
userLastOffsetModels, err := co.userLastOffsetDB.queryWithUID(loginUID)
if err != nil {
co.Error("查询用户偏移量失败!", zap.Error(err))
c.ResponseError(errors.New("查询用户偏移量失败!"))
return
}
if len(userLastOffsetModels) > 0 {
deviceOffsetList := make([]*deviceOffsetModel, 0, len(userLastOffsetModels))
for _, userLastOffsetM := range userLastOffsetModels {
deviceOffsetList = append(deviceOffsetList, &deviceOffsetModel{
UID: userLastOffsetM.UID,
DeviceUUID: req.DeviceUUID,
ChannelID: userLastOffsetM.ChannelID,
ChannelType: userLastOffsetM.ChannelType,
MessageSeq: userLastOffsetM.MessageSeq,
})
lastMsgSeqList = append(lastMsgSeqList, fmt.Sprintf("%s:%d:%d", userLastOffsetM.ChannelID, userLastOffsetM.ChannelType, userLastOffsetM.MessageSeq))
}
err := co.insertDeviceOffsets(deviceOffsetList)
if err != nil {
c.ResponseError(errors.New("插入设备偏移数据失败!"))
return
}
}
}
if len(lastMsgSeqList) > 0 {
lastMsgSeqs = strings.Join(lastMsgSeqList, "|")
}
}
}
// 获取用户的超大群
largeGroupInfos, err := co.groupService.GetUserSupers(loginUID)
if err != nil {
co.Error("获取用户超大群失败!", zap.Error(err))
c.ResponseError(errors.New("获取用户超大群失败!"))
return
}
largeChannels := make([]*config.Channel, 0)
if len(largeGroupInfos) > 0 {
for _, largeGroupInfo := range largeGroupInfos {
largeChannels = append(largeChannels, &config.Channel{
ChannelID: largeGroupInfo.GroupNo,
ChannelType: common.ChannelTypeGroup.Uint8(),
})
}
}
conversations, err := co.ctx.IMSyncUserConversation(loginUID, version, req.MsgCount, lastMsgSeqs, largeChannels)
if err != nil {
co.Error("同步离线后的最近会话失败!", zap.Error(err), zap.String("loginUID", loginUID))
c.ResponseError(errors.New("同步离线后的最近会话失败!"))
return
}
groupNos := make([]string, 0, len(conversations))
uids := make([]string, 0, len(conversations))
channelIDs := make([]string, 0, len(conversations))
if len(conversations) > 0 {
for _, conversation := range conversations {
if len(conversation.Recents) == 0 {
continue
}
if conversation.ChannelType == common.ChannelTypePerson.Uint8() {
uids = append(uids, conversation.ChannelID)
} else {
groupNos = append(groupNos, conversation.ChannelID)
}
channelIDs = append(channelIDs, conversation.ChannelID)
}
}
userMap := map[string]*user.UserDetailResp{} // 用户详情
groupMap := map[string]*group.GroupResp{} // 群详情
conversationExtraMap := map[string]*conversationExtraResp{} // 最近会话扩展
groupVailds := make([]string, 0, len(conversations)) // 有效群
// ---------- 是否在群内 ----------
if len(groupNos) > 0 {
groupVailds, err = co.groupService.ExistMembers(groupNos, loginUID)
if err != nil {
co.Error("查询有效群失败!", zap.Error(err))
c.ResponseError(errors.New("查询有效群失败!"))
return
}
}
// ---------- 扩展 ----------
conversationExtras, err := co.conversationExtraDB.queryWithChannelIDs(loginUID, channelIDs)
if err != nil {
co.Error("查询最近会话扩展失败!", zap.Error(err))
c.ResponseError(errors.New("查询最近会话扩展失败!"))
return
}
if len(conversationExtras) > 0 {
for _, conversationExtra := range conversationExtras {
conversationExtraMap[fmt.Sprintf("%s-%d", conversationExtra.ChannelID, conversationExtra.ChannelType)] = newConversationExtraResp(conversationExtra)
}
}
// ---------- 用户设置 ----------
users := make([]*user.UserDetailResp, 0)
if len(uids) > 0 {
users, err = co.userService.GetUserDetails(uids, c.GetLoginUID())
if err != nil {
co.Error("查询用户信息失败!", zap.Error(err))
c.ResponseError(errors.New("查询用户信息失败!"))
return
}
if len(users) > 0 {
for _, user := range users {
userMap[user.UID] = user
}
}
}
// ---------- 群设置 ----------
groups := make([]*group.GroupResp, 0)
if len(groupNos) > 0 {
groups, err = co.groupService.GetGroupDetails(groupNos, c.GetLoginUID())
if err != nil {
co.Error("查询群设置信息失败!", zap.Error(err))
c.ResponseError(errors.New("查询群设置信息失败!"))
return
}
if groups == nil {
groups = make([]*group.GroupResp, 0)
}
if len(groups) > 0 {
for _, group := range groups {
groupMap[group.GroupNo] = group
}
}
}
// ---------- 用户频道消息偏移 ----------
channelOffsetModelMap := map[string]*channelOffsetModel{}
if len(channelIDs) > 0 {
channelOffsetModels, err := co.channelOffsetDB.queryWithUIDAndChannelIDs(loginUID, channelIDs)
if err != nil {
co.Error("查询用户频道偏移量失败!", zap.Error(err))
c.ResponseError(errors.New("查询用户频道偏移量失败!"))
return
}
if len(channelOffsetModels) > 0 {
for _, channelOffsetM := range channelOffsetModels {
channelOffsetModelMap[fmt.Sprintf("%s-%d", channelOffsetM.ChannelID, channelOffsetM.ChannelType)] = channelOffsetM
}
}
}
// ---------- 频道设置 ----------
// channelSettings, err := co.channelService.GetChannelSettings(channelIDs)
// if err != nil {
// co.Error("查询频道设置失败!", zap.Error(err))
// c.ResponseError(errors.New("查询频道设置失败!"))
// return
// }
// channelSettingMap := map[string]*channel.ChannelSettingResp{}
// if len(channelSettings) > 0 {
// for _, channelSetting := range channelSettings {
// channelSettingMap[fmt.Sprintf("%s-%d", channelSetting.ChannelID, channelSetting.ChannelType)] = channelSetting
// }
// }
syncUserConversationResps := make([]*SyncUserConversationResp, 0, len(conversations))
userKey := loginUID
if len(conversations) > 0 {
for _, conversation := range conversations {
if conversation.ChannelType == common.ChannelTypeGroup.Uint8() {
vaild := false
for _, groupVaild := range groupVailds {
if groupVaild == conversation.ChannelID {
vaild = true
break
}
}
if !vaild { // 无效群则跳过
continue
}
}
var mute = 0
var stick = 0
if conversation.ChannelType == common.ChannelTypePerson.Uint8() {
userDetail := userMap[conversation.ChannelID]
if userDetail != nil {
mute = userDetail.Mute
stick = userDetail.Top
}
} else {
group := groupMap[conversation.ChannelID]
if group != nil {
mute = group.Mute
stick = group.Top
}
}
channelKey := fmt.Sprintf("%s-%d", conversation.ChannelID, conversation.ChannelType)
// channelSetting := channelSettingMap[channelKey]
channelOffsetM := channelOffsetModelMap[channelKey]
deviceOffsetM := deviceOffsetModelMap[channelKey]
extra := conversationExtraMap[channelKey]
syncUserConversationResp := newSyncUserConversationResp(conversation, extra, loginUID, co.messageExtraDB, co.messageReactionDB, co.messageUserExtraDB, mute, stick, channelOffsetM, deviceOffsetM)
if len(syncUserConversationResp.Recents) > 0 {
syncUserConversationResps = append(syncUserConversationResps, syncUserConversationResp)
}
// if channelSetting != nil {
// syncUserConversationResp.ParentChannelID = channelSetting.ParentChannelID
// syncUserConversationResp.ParentChannelType = channelSetting.ParentChannelType
// }
// 缓存频道对应的最新的消息messageSeq
if !co.ctx.GetConfig().MessageSaveAcrossDevice {
co.syncConversationResultCacheLock.RLock()
channelMessageSeqs := co.syncConversationResultCacheMap[userKey]
co.syncConversationResultCacheLock.RUnlock()
if channelMessageSeqs == nil {
channelMessageSeqs = make([]string, 0)
}
if len(syncUserConversationResp.Recents) > 0 {
channelMessageSeqs = append(channelMessageSeqs, co.channelMessageSeqJoin(conversation.ChannelID, conversation.ChannelType, syncUserConversationResp.Recents[0].MessageSeq))
co.syncConversationResultCacheLock.Lock()
co.syncConversationResultCacheMap[userKey] = channelMessageSeqs
co.syncConversationResultCacheLock.Unlock()
}
}
}
}
var lastVersion int64 = req.Version
if len(syncUserConversationResps) > 0 {
lastVersion = syncUserConversationResps[len(syncUserConversationResps)-1].Version
}
co.syncConversationResultCacheLock.Lock()
cacheVersion := co.syncConversationVersionMap[userKey]
if cacheVersion < lastVersion {
co.syncConversationVersionMap[userKey] = lastVersion
}
co.syncConversationResultCacheLock.Unlock()
c.Response(SyncUserConversationRespWrap{
Conversations: syncUserConversationResps,
UID: loginUID,
Users: users,
Groups: groups,
})
}
func (co *Conversation) channelMessageSeqJoin(channelID string, channelType uint8, lastMessageSeq uint32) string {
return fmt.Sprintf("%s:%d:%d", channelID, channelType, lastMessageSeq)
}
func (co *Conversation) channelMessageSeqSplit(channelMessageSeqStr string) (channelID string, channelType uint8, lastMessageSeq uint32) {
channelMessageSeqList := strings.Split(channelMessageSeqStr, ":")
if len(channelMessageSeqList) == 3 {
channelID = channelMessageSeqList[0]
channelTypeI64, _ := strconv.ParseInt(channelMessageSeqList[1], 10, 64)
channelType = uint8(channelTypeI64)
lastMessageSeqI64, _ := strconv.ParseInt(channelMessageSeqList[2], 10, 64)
lastMessageSeq = uint32(lastMessageSeqI64)
}
return
}
func (co *Conversation) syncUserConversationAck(c *wkhttp.Context) {
var req struct {
CMDVersion int64 `json:"cmd_version"` // cmd版本
DeviceUUID string `json:"device_uuid"` // 设备uuid
}
if err := c.BindJSON(&req); err != nil {
co.Error("数据格式有误!", zap.Error(err))
c.ResponseError(errors.New("数据格式有误!"))
return
}
if co.ctx.GetConfig().MessageSaveAcrossDevice {
c.ResponseOK()
return
}
loginUID := c.GetLoginUID()
userKey := loginUID
co.syncConversationResultCacheLock.RLock()
channelMessageSeqStrs := co.syncConversationResultCacheMap[userKey]
co.syncConversationResultCacheLock.RUnlock()
userLastOffsetModels := make([]*userLastOffsetModel, 0, len(channelMessageSeqStrs))
if len(channelMessageSeqStrs) > 0 {
for _, channelMessageSeqStr := range channelMessageSeqStrs {
channelID, channelType, messageSeq := co.channelMessageSeqSplit(channelMessageSeqStr)
var has bool
for _, userLastOffsetM := range userLastOffsetModels {
if channelID == userLastOffsetM.ChannelID && channelType == userLastOffsetM.ChannelType && messageSeq > uint32(userLastOffsetM.MessageSeq) {
userLastOffsetM.MessageSeq = int64(messageSeq)
has = true
break
}
}
if !has {
userLastOffsetModels = append(userLastOffsetModels, &userLastOffsetModel{
UID: loginUID,
ChannelID: channelID,
ChannelType: channelType,
MessageSeq: int64(messageSeq),
})
}
}
}
if len(userLastOffsetModels) > 0 {
err := co.insertUserLastOffsets(userLastOffsetModels)
if err != nil {
c.ResponseError(errors.New("插入设备偏移数据失败!"))
return
}
}
co.syncConversationResultCacheLock.RLock()
version := co.syncConversationVersionMap[userKey]
co.syncConversationResultCacheLock.RUnlock()
if version > 0 {
err := co.setUserConversationMaxVersion(loginUID, version)
if err != nil {
co.Error("设置设备最近会话最大版本号失败!", zap.Error(err))
c.ResponseError(errors.New("设置设备最近会话最大版本号失败!"))
return
}
}
c.ResponseOK()
}
func (co *Conversation) insertDeviceOffsets(deviceOffsetModels []*deviceOffsetModel) error {
tx, _ := co.ctx.DB().Begin()
defer func() {
if err := recover(); err != nil {
tx.RollbackUnlessCommitted()
panic(err)
}
}()
for _, deviceOffsetM := range deviceOffsetModels {
err := co.deviceOffsetDB.insertOrUpdateTx(tx, deviceOffsetM)
if err != nil {
tx.Rollback()
return err
}
}
if err := tx.Commit(); err != nil {
tx.Rollback()
co.Error("提交事务失败!", zap.Error(err))
return err
}
return nil
}
func (co *Conversation) insertUserLastOffsets(userLastOffsetModels []*userLastOffsetModel) error {
tx, _ := co.ctx.DB().Begin()
defer func() {
if err := recover(); err != nil {
tx.RollbackUnlessCommitted()
panic(err)
}
}()
for _, userLastOffsetM := range userLastOffsetModels {
err := co.userLastOffsetDB.insertOrUpdateTx(tx, userLastOffsetM)
if err != nil {
tx.Rollback()
return err
}
}
if err := tx.Commit(); err != nil {
tx.Rollback()
co.Error("提交事务失败!", zap.Error(err))
return err
}
return nil
}
func (co *Conversation) getDeviceConversationMaxVersion(uid string, deviceUUID string) (int64, error) {
versionStr, err := co.ctx.GetRedisConn().GetString(fmt.Sprintf("deviceMaxVersion:%s-%s", uid, deviceUUID))
if err != nil {
return 0, err
}
if versionStr == "" {
return 0, nil
}
return strconv.ParseInt(versionStr, 10, 64)
}
func (co *Conversation) setDeviceConversationMaxVersion(uid string, deviceUUID string, version int64) error {
err := co.ctx.GetRedisConn().Set(fmt.Sprintf("deviceMaxVersion:%s-%s", uid, deviceUUID), fmt.Sprintf("%d", version))
return err
}
func (co *Conversation) getUserConversationMaxVersion(uid string) (int64, error) {
versionStr, err := co.ctx.GetRedisConn().GetString(fmt.Sprintf("userMaxVersion:%s", uid))
if err != nil {
return 0, err
}
if versionStr == "" {
return 0, nil
}
return strconv.ParseInt(versionStr, 10, 64)
}
func (co *Conversation) setUserConversationMaxVersion(uid string, version int64) error {
err := co.ctx.GetRedisConn().Set(fmt.Sprintf("userMaxVersion:%s", uid), fmt.Sprintf("%d", version))
return err
}
// 获取最近会话列表
func (co *Conversation) getConversations(c *wkhttp.Context) {
loginUID := c.MustGet("uid").(string)
resps, err := co.ctx.IMGetConversations(loginUID)
if err != nil {
co.Error("获取最近会话失败!", zap.Error(err))
c.ResponseError(errors.New("获取最近会话失败!"))
return
}
conversationResps := make([]conversationResp, 0, len(resps))
userResps := make([]userResp, 0)
groupResps := make([]groupResp, 0)
if resps != nil {
userUIDs := make([]string, 0)
groupNos := make([]string, 0)
visitorNos := make([]string, 0)
for _, resp := range resps {
conversationResp := &conversationResp{}
conversationResp.from(resp, loginUID, nil, nil)
conversationResps = append(conversationResps, *conversationResp)
if resp.ChannelType == common.ChannelTypePerson.Uint8() {
userUIDs = append(userUIDs, resp.ChannelID)
} else {
if co.ctx.GetConfig().IsVisitorChannel(resp.ChannelID) {
visitorNo, _ := co.ctx.GetConfig().GetCustomerServiceVisitorUID(resp.ChannelID)
visitorNos = append(visitorNos, visitorNo)
} else {
groupNos = append(groupNos, resp.ChannelID)
}
}
}
userDetails, err := co.userDB.QueryDetailByUIDs(userUIDs, loginUID)
if err != nil {
co.Error("查询用户详情失败!")
c.ResponseError(errors.New("查询用户详情失败!"))
return
}
groupDetails, err := co.groupDB.QueryDetailWithGroupNos(groupNos, loginUID)
if err != nil {
co.Error("查询用户详情失败!")
c.ResponseError(errors.New("查询用户详情失败!"))
return
}
if len(userDetails) > 0 {
for _, userDetail := range userDetails {
userResp := userResp{}.from(userDetail, co.ctx.GetConfig().GetAvatarPath(userDetail.UID))
// if userDetail.UID == loginUID {
// userResp.Name = s.ctx.GetConfig().FileHelperName
// userResp.Avatar = s.ctx.GetConfig().FileHelperAvatar
// }
userResps = append(userResps, userResp)
}
}
if len(groupDetails) > 0 {
for _, group := range groupDetails {
groupResps = append(groupResps, groupResp{}.from(group))
}
}
}
c.JSON(http.StatusOK, conversationWrapResp{
Conversations: conversationResps,
Groups: groupResps,
Users: userResps,
})
}
// 清除最近会话未读数
func (co *Conversation) clearConversationUnread(c *wkhttp.Context) {
loginUID := c.MustGet("uid").(string)
var req clearConversationUnreadReq
if err := c.BindJSON(&req); err != nil {
co.Error("数据格式有误!", zap.Error(err))
c.ResponseError(common.ErrData)
return
}
// if co.ctx.GetConfig().IsVisitorChannel(req.ChannelID) {
// c.Request.URL.Path = "/v1/hotline/coversation/clearUnread"
// co.ctx.Server.GetRoute().HandleContext(c)
// return
// }
var messageSeq uint32 = 0
if req.ChannelType == common.ChannelTypeGroup.Uint8() {
groupInfo, err := co.groupService.GetGroupWithGroupNo(req.ChannelID)
if err != nil {
co.Error("查询群聊信息失败!", zap.Error(err))
c.ResponseError(errors.New("查询群聊信息失败!"))
return
}
if groupInfo != nil && groupInfo.GroupType == group.GroupTypeSuper {
messageSeq = req.MessageSeq // 只有超级群才传messageSeq
}
}
err := co.ctx.IMClearConversationUnread(config.ClearConversationUnreadReq{
UID: loginUID,
ChannelID: req.ChannelID,
ChannelType: req.ChannelType,
Unread: req.Unread,
MessageSeq: messageSeq,
})
if err != nil {
c.ResponseError(err)
return
}
// 发送清空红点的命令
err = co.ctx.SendCMD(config.MsgCMDReq{
NoPersist: true,
ChannelID: loginUID,
ChannelType: common.ChannelTypePerson.Uint8(),
CMD: common.CMDConversationUnreadClear,
Param: map[string]interface{}{
"channel_id": req.ChannelID,
"channel_type": req.ChannelType,
"unread": req.Unread,
},
})
if err != nil {
co.Error("命令发送失败!", zap.String("cmd", common.CMDConversationUnreadClear))
c.ResponseError(errors.New("命令发送失败!"))
return
}
c.ResponseOK()
}
// ---------- vo ----------
// SyncUserConversationRespWrap SyncUserConversationRespWrap
type SyncUserConversationRespWrap struct {
UID string `json:"uid"` // 请求者uid
Conversations []*SyncUserConversationResp `json:"conversations"`
Users []*user.UserDetailResp `json:"users"` // 用户详情
Groups []*group.GroupResp `json:"groups"` // 群
}
type clearConversationUnreadReq struct {
ChannelID string `json:"channel_id"`
ChannelType uint8 `json:"channel_type"`
Unread int `json:"unread"` // 未读数量 0表示清空所有未读数量
MessageSeq uint32 `json:"message_seq"`
}
type conversationResp struct {
ChannelID string `json:"channel_id"` // 频道ID
ChannelType uint8 `json:"channel_type"` // 频道类型
Unread int64 `json:"unread"` // 未读数
Timestamp int64 `json:"timestamp"` // 最后一次会话时间戳
LastMessage *MsgSyncResp `json:"last_message"` // 最后一条消息
}
type conversationWrapResp struct {
Conversations []conversationResp `json:"conversations"` // 最近会话
Groups []groupResp `json:"groups"` // 群组集合
Users []userResp `json:"users"` // 好友集合
}
func (m *conversationResp) from(resp *config.ConversationResp, loginUID string, messageExtra *messageExtraDetailModel, messageUserExtraM *messageUserExtraModel) {
m.ChannelID = resp.ChannelID
m.ChannelType = resp.ChannelType
m.Unread = resp.Unread
m.Timestamp = resp.Timestamp
msgSyncResp := &MsgSyncResp{}
msgSyncResp.from(resp.LastMessage, loginUID, messageExtra, messageUserExtraM, nil)
m.LastMessage = msgSyncResp
}
type conversationExtraResp struct {
ChannelID string `json:"channel_id"`
ChannelType uint8 `json:"channel_type"`
BrowseTo uint32 `json:"browse_to"`
KeepMessageSeq uint32 `json:"keep_message_seq"`
KeepOffsetY int `json:"keep_offset_y"`
Draft string `json:"draft"` // 草稿
Version int64 `json:"version"`
}
func newConversationExtraResp(m *conversationExtraModel) *conversationExtraResp {
return &conversationExtraResp{
ChannelID: m.ChannelID,
ChannelType: m.ChannelType,
BrowseTo: m.BrowseTo,
KeepMessageSeq: m.KeepMessageSeq,
KeepOffsetY: m.KeepOffsetY,
Draft: m.Draft,
Version: m.Version,
}
}
type groupResp struct {
GroupNo string `json:"group_no"` // 群编号
Name string `json:"name"` // 群名称
Notice string `json:"notice"` // 群公告
Mute int `json:"mute"` // 免打扰
Top int `json:"top"` // 置顶
ShowNick int `json:"show_nick"` // 显示昵称
Save int `json:"save"` // 是否保存
Forbidden int `json:"forbidden"` // 是否全员禁言
Invite int `json:"invite"` // 群聊邀请确认
}
func (g groupResp) from(group *group.DetailModel) groupResp {
return groupResp{
GroupNo: group.GroupNo,
Name: group.Name,
Notice: group.Notice,
Mute: group.Mute,
Top: group.Top,
ShowNick: group.ShowNick,
Save: group.Save,
Forbidden: group.Forbidden,
Invite: group.Invite,
}
}
type userResp struct {
ID int64 `json:"id"`
UID string `json:"uid"` // 好友uid
Name string `json:"name"` // 好友名称
Avatar string `json:"avatar"` // 头像
Mute int `json:"mute"`
Top int `json:"top"`
Online int `json:"online"` // 是否在线
}
func (u userResp) from(user *user.Detail, avatarPath string) userResp {
return userResp{
ID: user.Id,
UID: user.UID,
Name: user.Name,
Mute: user.Mute,
Top: user.Top,
Avatar: avatarPath,
}
}
// type messageHeader struct {
// NoPersist int `json:"no_persist"` // 是否不持久化
// RedDot int `json:"red_dot"` // 是否显示红点
// SyncOnce int `json:"sync_once"` // 此消息只被同步或被消费一次
// }
// type msgSyncResp struct {
// Header messageHeader `json:"header"` // 消息头部
// MessageID int64 `json:"message_id"` // 服务端的消息ID(全局唯一)
// MessageIDStr string `json:"message_idstr"` // 服务端的消息ID(全局唯一)
// MessageSeq uint32 `json:"message_seq"` // 消息序列号 (用户唯一,有序递增)
// ClientMsgNo string `json:"client_msg_no"` // 客户端消息唯一编号
// FromUID string `json:"from_uid"` // 发送者UID
// ToUID string `json:"to_uid"` // 接受者uid
// ChannelID string `json:"channel_id"` // 频道ID
// ChannelType uint8 `json:"channel_type"` // 频道类型
// Timestamp int32 `json:"timestamp"` // 服务器消息时间戳(10位,到秒)
// Payload map[string]interface{} `json:"payload"` // 消息内容
// IsDeleted uint8 `json:"is_deleted"` // 是否已删除
// }
// func (m *msgSyncResp) from(msgResp *config.MessageResp, loginUID string) {
// m.Header.NoPersist = msgResp.Header.NoPersist
// m.Header.RedDot = msgResp.Header.RedDot
// m.Header.SyncOnce = msgResp.Header.SyncOnce
// m.MessageID = msgResp.MessageID
// m.MessageIDStr = strconv.FormatInt(msgResp.MessageID, 10)
// m.MessageSeq = msgResp.MessageSeq
// m.ClientMsgNo = msgResp.ClientMsgNo
// m.FromUID = msgResp.FromUID
// m.ToUID = msgResp.ToUID
// m.ChannelID = msgResp.ChannelID
// m.ChannelType = msgResp.ChannelType
// m.Timestamp = msgResp.Timestamp
// var payloadMap map[string]interface{}
// err := util.ReadJsonByByte(msgResp.Payload, &payloadMap)
// if err != nil {
// log.Warn("负荷数据不是json格式!", zap.Error(err), zap.String("payload", string(msgResp.Payload)))
// }
// if len(payloadMap) > 0 {
// visibles := payloadMap["visibles"]
// if visibles != nil {
// visiblesArray := visibles.([]interface{})
// if len(visiblesArray) > 0 {
// m.IsDeleted = 1
// for _, limitUID := range visiblesArray {
// if limitUID == loginUID {
// m.IsDeleted = 0
// }
// }
// }
// }
// }
// m.Payload = payloadMap
// }
// SyncUserConversationResp 最近会话离线返回
type SyncUserConversationResp struct {
ChannelID string `json:"channel_id"` // 频道ID
ChannelType uint8 `json:"channel_type"` // 频道类型
Unread int `json:"unread,omitempty"` // 未读消息
Mute int `json:"mute,omitempty"` // 免打扰
Stick int `json:"stick,omitempty"` // 置顶
Timestamp int64 `json:"timestamp"` // 最后一次会话时间
LastMsgSeq int64 `json:"last_msg_seq"` // 最后一条消息seq
LastClientMsgNo string `json:"last_client_msg_no"` // 最后一条客户端消息编号
OffsetMsgSeq int64 `json:"offset_msg_seq"` // 偏移位的消息seq