-
Notifications
You must be signed in to change notification settings - Fork 249
/
message_persistence.go
3096 lines (2740 loc) · 81.4 KB
/
message_persistence.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 protocol
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/golang/protobuf/proto"
"github.com/lib/pq"
"github.com/status-im/status-go/protocol/common"
"github.com/status-im/status-go/protocol/protobuf"
)
var basicMessagesSelectQuery = `
SELECT %s %s
FROM user_messages m1
LEFT JOIN user_messages m2
ON m1.response_to = m2.id
LEFT JOIN contacts c
ON m1.source = c.id
LEFT JOIN discord_messages dm
ON m1.discord_message_id = dm.id
LEFT JOIN discord_message_authors dm_author
ON dm.author_id = dm_author.id
LEFT JOIN discord_message_attachments dm_attachment
ON dm.id = dm_attachment.discord_message_id
LEFT JOIN discord_messages m2_dm
ON m2.discord_message_id = m2_dm.id
LEFT JOIN discord_message_authors m2_dm_author
ON m2_dm.author_id = m2_dm_author.id
LEFT JOIN bridge_messages bm
ON m1.id = bm.user_messages_id
LEFT JOIN bridge_messages bm_response
ON m2.id = bm_response.user_messages_id
`
var basicInsertDiscordMessageAuthorQuery = `INSERT OR REPLACE INTO discord_message_authors(id,name,discriminator,nickname,avatar_url, avatar_image_payload) VALUES (?,?,?,?,?,?)`
var cursor = "substr('0000000000000000000000000000000000000000000000000000000000000000' || m1.clock_value, -64, 64) || m1.id"
var cursorField = cursor + " as cursor"
func (db sqlitePersistence) buildMessagesQueryWithAdditionalFields(additionalSelectFields, whereAndTheRest string) string {
allFields := db.tableUserMessagesAllFieldsJoin()
if additionalSelectFields != "" {
additionalSelectFields = "," + additionalSelectFields
}
base := fmt.Sprintf(basicMessagesSelectQuery, allFields, additionalSelectFields)
return base + " " + whereAndTheRest
}
func (db sqlitePersistence) buildMessagesQuery(whereAndTheRest string) string {
return db.buildMessagesQueryWithAdditionalFields("", whereAndTheRest)
}
func (db sqlitePersistence) tableUserMessagesAllFields() string {
return `id,
whisper_timestamp,
source,
text,
content_type,
username,
timestamp,
chat_id,
local_chat_id,
message_type,
clock_value,
seen,
outgoing_status,
parsed_text,
sticker_pack,
sticker_hash,
image_payload,
image_type,
album_id,
album_images,
album_images_count,
image_width,
image_height,
image_base64,
audio_payload,
audio_type,
audio_duration_ms,
audio_base64,
community_id,
mentions,
links,
unfurled_links,
unfurled_status_links,
command_id,
command_value,
command_from,
command_address,
command_contract,
command_transaction_hash,
command_state,
command_signature,
replace_message,
edited_at,
deleted,
deleted_by,
deleted_for_me,
rtl,
line_count,
response_to,
gap_from,
gap_to,
contact_request_state,
contact_verification_status,
mentioned,
replied,
discord_message_id`
}
// keep the same order as in tableUserMessagesScanAllFields
func (db sqlitePersistence) tableUserMessagesAllFieldsJoin() string {
return `m1.id,
m1.whisper_timestamp,
m1.source,
m1.text,
m1.content_type,
m1.username,
m1.timestamp,
m1.chat_id,
m1.local_chat_id,
m1.message_type,
m1.clock_value,
m1.seen,
m1.outgoing_status,
m1.parsed_text,
m1.sticker_pack,
m1.sticker_hash,
m1.image_payload,
m1.image_type,
COALESCE(m1.album_id, ""),
COALESCE(m1.album_images_count, 0),
COALESCE(m1.image_width, 0),
COALESCE(m1.image_height, 0),
COALESCE(m1.audio_duration_ms,0),
m1.community_id,
m1.mentions,
m1.links,
m1.unfurled_links,
m1.unfurled_status_links,
m1.command_id,
m1.command_value,
m1.command_from,
m1.command_address,
m1.command_contract,
m1.command_transaction_hash,
m1.command_state,
m1.command_signature,
m1.replace_message,
m1.edited_at,
m1.deleted,
m1.deleted_by,
m1.deleted_for_me,
m1.rtl,
m1.line_count,
m1.response_to,
m1.gap_from,
m1.gap_to,
m1.contact_request_state,
m1.contact_verification_status,
m1.mentioned,
m1.replied,
COALESCE(m1.discord_message_id, ""),
COALESCE(dm.author_id, ""),
COALESCE(dm.type, ""),
COALESCE(dm.timestamp, ""),
COALESCE(dm.timestamp_edited, ""),
COALESCE(dm.content, ""),
COALESCE(dm.reference_message_id, ""),
COALESCE(dm.reference_channel_id, ""),
COALESCE(dm_author.name, ""),
COALESCE(dm_author.discriminator, ""),
COALESCE(dm_author.nickname, ""),
COALESCE(dm_author.avatar_url, ""),
COALESCE(dm_attachment.id, ""),
COALESCE(dm_attachment.discord_message_id, ""),
COALESCE(dm_attachment.url, ""),
COALESCE(dm_attachment.file_name, ""),
COALESCE(dm_attachment.content_type, ""),
m2.source,
m2.text,
m2.parsed_text,
m2.album_images,
m2.album_images_count,
m2.audio_duration_ms,
m2.community_id,
m2.id,
m2.content_type,
m2.deleted,
m2.deleted_for_me,
c.alias,
c.identicon,
COALESCE(m2.discord_message_id, ""),
COALESCE(m2_dm_author.name, ""),
COALESCE(m2_dm_author.nickname, ""),
COALESCE(m2_dm_author.avatar_url, ""),
COALESCE(bm.bridge_name, ""),
COALESCE(bm.user_name, ""),
COALESCE(bm.user_avatar, ""),
COALESCE(bm.user_id, ""),
COALESCE(bm.content, ""),
COALESCE(bm.message_id, ""),
COALESCE(bm.parent_message_id, ""),
COALESCE(bm_response.bridge_name, ""),
COALESCE(bm_response.user_name, ""),
COALESCE(bm_response.user_avatar, ""),
COALESCE(bm_response.user_id, ""),
COALESCE(bm_response.content, "")`
}
func (db sqlitePersistence) tableUserMessagesAllFieldsCount() int {
return strings.Count(db.tableUserMessagesAllFields(), ",") + 1
}
type scanner interface {
Scan(dest ...interface{}) error
}
// keep the same order as in tableUserMessagesAllFieldsJoin
func (db sqlitePersistence) tableUserMessagesScanAllFields(row scanner, message *common.Message, others ...interface{}) error {
var quotedID sql.NullString
var ContentType sql.NullInt64
var quotedText sql.NullString
var quotedParsedText []byte
var quotedAlbumImages []byte
var quotedAlbumImagesCount sql.NullInt64
var quotedFrom sql.NullString
var quotedAudioDuration sql.NullInt64
var quotedCommunityID sql.NullString
var quotedDeleted sql.NullBool
var quotedDeletedForMe sql.NullBool
var serializedMentions []byte
var serializedLinks []byte
var serializedUnfurledLinks []byte
var serializedUnfurledStatusLinks []byte
var alias sql.NullString
var identicon sql.NullString
var communityID sql.NullString
var gapFrom sql.NullInt64
var gapTo sql.NullInt64
var editedAt sql.NullInt64
var deleted sql.NullBool
var deletedBy sql.NullString
var deletedForMe sql.NullBool
var contactRequestState sql.NullInt64
var contactVerificationState sql.NullInt64
sticker := &protobuf.StickerMessage{}
command := &common.CommandParameters{}
audio := &protobuf.AudioMessage{}
image := &protobuf.ImageMessage{}
discordMessage := &protobuf.DiscordMessage{
Author: &protobuf.DiscordMessageAuthor{},
Reference: &protobuf.DiscordMessageReference{},
Attachments: []*protobuf.DiscordMessageAttachment{},
}
bridgeMessage := &protobuf.BridgeMessage{}
quotedBridgeMessage := &protobuf.BridgeMessage{}
quotedDiscordMessage := &protobuf.DiscordMessage{
Author: &protobuf.DiscordMessageAuthor{},
}
attachment := &protobuf.DiscordMessageAttachment{}
args := []interface{}{
&message.ID,
&message.WhisperTimestamp,
&message.From, // source in table
&message.Text,
&message.ContentType,
&message.Alias,
&message.Timestamp,
&message.ChatId,
&message.LocalChatID,
&message.MessageType,
&message.Clock,
&message.Seen,
&message.OutgoingStatus,
&message.ParsedText,
&sticker.Pack,
&sticker.Hash,
&image.Payload,
&image.Format,
&image.AlbumId,
&image.AlbumImagesCount,
&image.Width,
&image.Height,
&audio.DurationMs,
&communityID,
&serializedMentions,
&serializedLinks,
&serializedUnfurledLinks,
&serializedUnfurledStatusLinks,
&command.ID,
&command.Value,
&command.From,
&command.Address,
&command.Contract,
&command.TransactionHash,
&command.CommandState,
&command.Signature,
&message.Replace,
&editedAt,
&deleted,
&deletedBy,
&deletedForMe,
&message.RTL,
&message.LineCount,
&message.ResponseTo,
&gapFrom,
&gapTo,
&contactRequestState,
&contactVerificationState,
&message.Mentioned,
&message.Replied,
&discordMessage.Id,
&discordMessage.Author.Id,
&discordMessage.Type,
&discordMessage.Timestamp,
&discordMessage.TimestampEdited,
&discordMessage.Content,
&discordMessage.Reference.MessageId,
&discordMessage.Reference.ChannelId,
&discordMessage.Author.Name,
&discordMessage.Author.Discriminator,
&discordMessage.Author.Nickname,
&discordMessage.Author.AvatarUrl,
&attachment.Id,
&attachment.MessageId,
&attachment.Url,
&attachment.FileName,
&attachment.ContentType,
"edFrom,
"edText,
"edParsedText,
"edAlbumImages,
"edAlbumImagesCount,
"edAudioDuration,
"edCommunityID,
"edID,
&ContentType,
"edDeleted,
"edDeletedForMe,
&alias,
&identicon,
"edDiscordMessage.Id,
"edDiscordMessage.Author.Name,
"edDiscordMessage.Author.Nickname,
"edDiscordMessage.Author.AvatarUrl,
&bridgeMessage.BridgeName,
&bridgeMessage.UserName,
&bridgeMessage.UserAvatar,
&bridgeMessage.UserID,
&bridgeMessage.Content,
&bridgeMessage.MessageID,
&bridgeMessage.ParentMessageID,
"edBridgeMessage.BridgeName,
"edBridgeMessage.UserName,
"edBridgeMessage.UserAvatar,
"edBridgeMessage.UserID,
"edBridgeMessage.Content,
}
err := row.Scan(append(args, others...)...)
if err != nil {
return err
}
if editedAt.Valid {
message.EditedAt = uint64(editedAt.Int64)
}
if deleted.Valid {
message.Deleted = deleted.Bool
}
if deletedBy.Valid {
message.DeletedBy = deletedBy.String
}
if deletedForMe.Valid {
message.DeletedForMe = deletedForMe.Bool
}
if contactRequestState.Valid {
message.ContactRequestState = common.ContactRequestState(contactRequestState.Int64)
}
if contactVerificationState.Valid {
message.ContactVerificationState = common.ContactVerificationState(contactVerificationState.Int64)
}
if quotedText.Valid {
if quotedDeleted.Bool || quotedDeletedForMe.Bool {
message.QuotedMessage = &common.QuotedMessage{
ID: quotedID.String,
From: quotedFrom.String,
Deleted: quotedDeleted.Bool,
DeletedForMe: quotedDeletedForMe.Bool,
}
} else {
message.QuotedMessage = &common.QuotedMessage{
ID: quotedID.String,
ContentType: ContentType.Int64,
From: quotedFrom.String,
Text: quotedText.String,
ParsedText: quotedParsedText,
AlbumImages: quotedAlbumImages,
AlbumImagesCount: quotedAlbumImagesCount.Int64,
CommunityID: quotedCommunityID.String,
Deleted: quotedDeleted.Bool,
}
if message.QuotedMessage.ContentType == int64(protobuf.ChatMessage_DISCORD_MESSAGE) {
message.QuotedMessage.DiscordMessage = quotedDiscordMessage
}
if message.QuotedMessage.ContentType == int64(protobuf.ChatMessage_BRIDGE_MESSAGE) {
message.QuotedMessage.BridgeMessage = quotedBridgeMessage
}
}
}
message.Alias = alias.String
message.Identicon = identicon.String
if gapFrom.Valid && gapTo.Valid {
message.GapParameters = &common.GapParameters{
From: uint32(gapFrom.Int64),
To: uint32(gapTo.Int64),
}
}
if communityID.Valid {
message.CommunityID = communityID.String
}
if serializedMentions != nil {
err := json.Unmarshal(serializedMentions, &message.Mentions)
if err != nil {
return err
}
}
if serializedLinks != nil {
err := json.Unmarshal(serializedLinks, &message.Links)
if err != nil {
return err
}
}
if serializedUnfurledLinks != nil {
err = json.Unmarshal(serializedUnfurledLinks, &message.UnfurledLinks)
if err != nil {
return err
}
}
if serializedUnfurledStatusLinks != nil {
// use proto.Marshal, because json.Marshal doesn't support `oneof` fields
var links protobuf.UnfurledStatusLinks
err = proto.Unmarshal(serializedUnfurledStatusLinks, &links)
if err != nil {
return err
}
message.UnfurledStatusLinks = &links
}
if attachment.Id != "" {
discordMessage.Attachments = append(discordMessage.Attachments, attachment)
}
switch message.ContentType {
case protobuf.ChatMessage_STICKER:
message.Payload = &protobuf.ChatMessage_Sticker{Sticker: sticker}
case protobuf.ChatMessage_AUDIO:
message.Payload = &protobuf.ChatMessage_Audio{Audio: audio}
case protobuf.ChatMessage_TRANSACTION_COMMAND:
message.CommandParameters = command
case protobuf.ChatMessage_IMAGE:
message.Payload = &protobuf.ChatMessage_Image{Image: image}
case protobuf.ChatMessage_DISCORD_MESSAGE:
message.Payload = &protobuf.ChatMessage_DiscordMessage{
DiscordMessage: discordMessage,
}
case protobuf.ChatMessage_BRIDGE_MESSAGE:
message.Payload = &protobuf.ChatMessage_BridgeMessage{
BridgeMessage: bridgeMessage,
}
}
return nil
}
func (db sqlitePersistence) tableUserMessagesAllValues(message *common.Message) ([]interface{}, error) {
var gapFrom, gapTo uint32
var albumImages []byte
if message.QuotedMessage != nil {
albumImages = []byte(message.QuotedMessage.AlbumImages)
}
sticker := message.GetSticker()
if sticker == nil {
sticker = &protobuf.StickerMessage{}
}
image := message.GetImage()
if image == nil {
image = &protobuf.ImageMessage{}
}
audio := message.GetAudio()
if audio == nil {
audio = &protobuf.AudioMessage{}
}
command := message.CommandParameters
if command == nil {
command = &common.CommandParameters{}
}
discordMessage := message.GetDiscordMessage()
if discordMessage == nil {
discordMessage = &protobuf.DiscordMessage{
Author: &protobuf.DiscordMessageAuthor{},
Reference: &protobuf.DiscordMessageReference{},
Attachments: make([]*protobuf.DiscordMessageAttachment, 0),
}
}
if message.GapParameters != nil {
gapFrom = message.GapParameters.From
gapTo = message.GapParameters.To
}
var serializedMentions []byte
var err error
if len(message.Mentions) != 0 {
serializedMentions, err = json.Marshal(message.Mentions)
if err != nil {
return nil, err
}
}
var serializedLinks []byte
if len(message.Links) != 0 {
serializedLinks, err = json.Marshal(message.Links)
if err != nil {
return nil, err
}
}
var serializedUnfurledLinks []byte
if links := message.GetUnfurledLinks(); links != nil {
serializedUnfurledLinks, err = json.Marshal(links)
if err != nil {
return nil, err
}
}
var serializedUnfurledStatusLinks []byte
if links := message.GetUnfurledStatusLinks(); links != nil {
// use proto.Marshal, because json.Marshal doesn't support `oneof` fields
serializedUnfurledStatusLinks, err = proto.Marshal(links)
if err != nil {
return nil, err
}
}
return []interface{}{
message.ID,
message.WhisperTimestamp,
message.From, // source in table
message.Text,
message.ContentType,
message.Alias,
message.Timestamp,
message.ChatId,
message.LocalChatID,
message.MessageType,
message.Clock,
message.Seen,
message.OutgoingStatus,
message.ParsedText,
sticker.Pack,
sticker.Hash,
image.Payload,
image.Format,
image.AlbumId,
albumImages,
image.AlbumImagesCount,
image.Width,
image.Height,
message.Base64Image,
audio.Payload,
audio.Type,
audio.DurationMs,
message.Base64Audio,
message.CommunityID,
serializedMentions,
serializedLinks,
serializedUnfurledLinks,
serializedUnfurledStatusLinks,
command.ID,
command.Value,
command.From,
command.Address,
command.Contract,
command.TransactionHash,
command.CommandState,
command.Signature,
message.Replace,
int64(message.EditedAt),
message.Deleted,
message.DeletedBy,
message.DeletedForMe,
message.RTL,
message.LineCount,
message.ResponseTo,
gapFrom,
gapTo,
message.ContactRequestState,
message.ContactVerificationState,
message.Mentioned,
message.Replied,
discordMessage.Id,
}, nil
}
func (db sqlitePersistence) messageByID(tx *sql.Tx, id string) (*common.Message, error) {
var err error
if tx == nil {
tx, err = db.db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return nil, err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
// don't shadow original error
_ = tx.Rollback()
}()
}
query := db.buildMessagesQuery("WHERE m1.id = ?")
rows, err := tx.Query(query, id)
if err != nil {
return nil, err
}
defer rows.Close()
return getMessageFromScanRows(db, rows)
}
func (db sqlitePersistence) albumMessages(chatID, albumID string) ([]*common.Message, error) {
if albumID == "" {
return nil, nil
}
query := db.buildMessagesQuery("WHERE m1.album_id = ? and m1.local_chat_id = ?")
rows, err := db.db.Query(query, albumID, chatID)
if err != nil {
return nil, err
}
defer rows.Close()
return getMessagesFromScanRows(db, rows, false)
}
func (db sqlitePersistence) MessageByCommandID(chatID, id string) (*common.Message, error) {
where := `WHERE
m1.command_id = ?
AND
m1.local_chat_id = ?
ORDER BY m1.clock_value DESC
LIMIT 1`
query := db.buildMessagesQuery(where)
rows, err := db.db.Query(query, id, chatID)
if err != nil {
return nil, err
}
defer rows.Close()
return getMessageFromScanRows(db, rows)
}
func (db sqlitePersistence) MessageByID(id string) (*common.Message, error) {
return db.messageByID(nil, id)
}
func (db sqlitePersistence) AlbumMessages(chatID, albumID string) ([]*common.Message, error) {
return db.albumMessages(chatID, albumID)
}
func (db sqlitePersistence) MessagesExist(ids []string) (map[string]bool, error) {
result := make(map[string]bool)
if len(ids) == 0 {
return result, nil
}
idsArgs := make([]interface{}, 0, len(ids))
for _, id := range ids {
idsArgs = append(idsArgs, id)
}
inVector := strings.Repeat("?, ", len(ids)-1) + "?"
query := "SELECT id FROM user_messages WHERE id IN (" + inVector + ")" // nolint: gosec
rows, err := db.db.Query(query, idsArgs...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id string
err := rows.Scan(&id)
if err != nil {
return nil, err
}
result[id] = true
}
return result, nil
}
func (db sqlitePersistence) MessagesByIDs(ids []string) ([]*common.Message, error) {
if len(ids) == 0 {
return nil, nil
}
idsArgs := make([]interface{}, 0, len(ids))
for _, id := range ids {
idsArgs = append(idsArgs, id)
}
inVector := strings.Repeat("?, ", len(ids)-1) + "?"
// nolint: gosec
where := fmt.Sprintf("WHERE NOT(m1.hide) AND m1.id IN (%s)", inVector)
query := db.buildMessagesQuery(where)
rows, err := db.db.Query(query, idsArgs...)
if err != nil {
return nil, err
}
defer rows.Close()
return getMessagesFromScanRows(db, rows, false)
}
func (db sqlitePersistence) MessagesByResponseTo(responseTo string) ([]*common.Message, error) {
where := "WHERE m1.response_to = ?"
query := db.buildMessagesQuery(where)
rows, err := db.db.Query(query, responseTo)
if err != nil {
return nil, err
}
defer rows.Close()
return getMessagesFromScanRows(db, rows, false)
}
// MessageByChatID returns all messages for a given chatID in descending order.
// Ordering is accomplished using two concatenated values: ClockValue and ID.
// These two values are also used to compose a cursor which is returned to the result.
func (db sqlitePersistence) MessageByChatID(chatID string, currCursor string, limit int) ([]*common.Message, string, error) {
cursorWhere := ""
if currCursor != "" {
cursorWhere = "AND cursor <= ?" //nolint: goconst
}
args := []interface{}{chatID}
if currCursor != "" {
args = append(args, currCursor)
}
// Build a new column `cursor` at the query time by having a fixed-sized clock value at the beginning
// concatenated with message ID. Results are sorted using this new column.
// This new column values can also be returned as a cursor for subsequent requests.
where := fmt.Sprintf(`
WHERE
NOT(m1.hide) AND m1.local_chat_id = ? %s
ORDER BY cursor DESC
LIMIT ?`, cursorWhere)
query := db.buildMessagesQueryWithAdditionalFields(cursorField, where)
rows, err := db.db.Query(
query,
append(args, limit+1)..., // take one more to figure our whether a cursor should be returned
)
if err != nil {
return nil, "", err
}
defer rows.Close()
result, cursors, err := getMessagesAndCursorsFromScanRows(db, rows)
if err != nil {
return nil, "", err
}
var newCursor string
if len(result) > limit {
newCursor = cursors[limit]
result = result[:limit]
}
return result, newCursor, nil
}
func (db sqlitePersistence) FirstUnseenMessageID(chatID string) (string, error) {
var id string
err := db.db.QueryRow(`
SELECT
id
FROM
user_messages m1
WHERE
m1.local_chat_id = ?
AND NOT(m1.seen) AND NOT(m1.hide) AND NOT(m1.deleted) AND NOT(m1.deleted_for_me)
ORDER BY m1.clock_value ASC
LIMIT 1`,
chatID).Scan(&id)
if err == sql.ErrNoRows {
return "", nil
}
if err != nil {
return "", err
}
return id, nil
}
// Get last chat message that is not hide or deleted or deleted_for_me
func (db sqlitePersistence) LatestMessageByChatID(chatID string) ([]*common.Message, error) {
args := []interface{}{chatID}
where := `WHERE
NOT(m1.hide) AND NOT(m1.deleted) AND NOT(m1.deleted_for_me) AND m1.local_chat_id = ?
ORDER BY cursor DESC
LIMIT ?`
query := db.buildMessagesQueryWithAdditionalFields(cursorField, where)
rows, err := db.db.Query(
query,
append(args, 2)..., // take one more to figure our whether a cursor should be returned
)
if err != nil {
return nil, err
}
defer rows.Close()
result, _, err := getMessagesAndCursorsFromScanRows(db, rows)
if err != nil {
return nil, err
}
if len(result) > 1 {
result = result[:1]
}
return result, nil
}
func (db sqlitePersistence) latestIncomingMessageClock(chatID string) (uint64, error) {
var clock uint64
err := db.db.QueryRow(
fmt.Sprintf(
`
SELECT
clock_value
FROM
user_messages m1
WHERE
m1.local_chat_id = ? AND m1.outgoing_status = ''
%s DESC
LIMIT 1
`, cursor),
chatID).Scan(&clock)
if err != nil {
return 0, err
}
return clock, nil
}
func (db sqlitePersistence) PendingContactRequests(currCursor string, limit int) ([]*common.Message, string, error) {
cursorWhere := ""
if currCursor != "" {
cursorWhere = "AND cursor <= ?" //nolint: goconst
}
args := []interface{}{protobuf.ChatMessage_CONTACT_REQUEST}
if currCursor != "" {
args = append(args, currCursor)
}
// Build a new column `cursor` at the query time by having a fixed-sized clock value at the beginning
// concatenated with message ID. Results are sorted using this new column.
// This new column values can also be returned as a cursor for subsequent requests.
where := fmt.Sprintf(`
WHERE
NOT(m1.hide) AND NOT(m1.seen) AND m1.content_type = ? %s
ORDER BY cursor DESC
LIMIT ?`, cursorWhere)
query := db.buildMessagesQueryWithAdditionalFields(cursorField, where)
rows, err := db.db.Query(
query,
append(args, limit+1)..., // take one more to figure our whether a cursor should be returned
)
if err != nil {
return nil, "", err
}
defer rows.Close()
result, cursors, err := getMessagesAndCursorsFromScanRows(db, rows)
if err != nil {
return nil, "", err
}
var newCursor string
if len(result) > limit {
newCursor = cursors[limit]
result = result[:limit]
}
return result, newCursor, nil
}
func (db sqlitePersistence) LatestPendingContactRequestIDForContact(contactID string) (string, error) {
var id string
err := db.db.QueryRow(
fmt.Sprintf(
`
SELECT
id
FROM
user_messages m1
WHERE
m1.local_chat_id = ? AND m1.content_type = ?
ORDER BY %s DESC
LIMIT 1
`, cursor),
contactID, protobuf.ChatMessage_CONTACT_REQUEST).Scan(&id)
if err == sql.ErrNoRows {
return "", nil
}
if err != nil {
return "", err
}
return id, nil
}
func (db sqlitePersistence) LatestContactRequests() ([]LatestContactRequest, error) {
res := make([]LatestContactRequest, 0)
rows, err := db.db.Query(
fmt.Sprintf(
`
SELECT
id, contact_request_state, local_chat_id
FROM
user_messages m1
WHERE
m1.content_type = ?
ORDER BY %s DESC
LIMIT 200
`, cursor), protobuf.ChatMessage_CONTACT_REQUEST)
if err != nil {
return res, err
}
defer rows.Close()
for rows.Next() {
var id string
var contactRequestState sql.NullInt64
var localChatID string
err := rows.Scan(&id, &contactRequestState, &localChatID)
if err != nil {
return nil, err
}
res = append(res, LatestContactRequest{
MessageID: id,
ContactRequestState: common.ContactRequestState(contactRequestState.Int64),
ContactID: localChatID,
})
}
return res, nil
}
// AllMessageByChatIDWhichMatchPattern returns all messages which match the search
// term, for a given chatID in descending order.
// Ordering is accomplished using two concatenated values: ClockValue and ID.
// These two values are also used to compose a cursor which is returned to the result.
func (db sqlitePersistence) AllMessageByChatIDWhichMatchTerm(chatID string, searchTerm string, caseSensitive bool) ([]*common.Message, error) {
if searchTerm == "" {
return nil, fmt.Errorf("empty search term")