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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
|
package telegram
import (
"crypto/sha1"
"fmt"
"github.com/pkg/errors"
"io"
"io/ioutil"
"net/http"
"os"
osUser "os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"dev.narayana.im/narayana/telegabber/telegram/cache"
"dev.narayana.im/narayana/telegabber/telegram/formatter"
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
log "github.com/sirupsen/logrus"
"github.com/soheilhy/args"
"github.com/zelenin/go-tdlib/client"
)
type VCardInfo struct {
Fn string
Photo *client.File
Nickname string
Given string
Family string
Tel string
Info string
}
var errOffline = errors.New("TDlib instance is offline")
var spaceRegex = regexp.MustCompile(`\s+`)
var replyRegex = regexp.MustCompile("\\A>>? ?([0-9]+)\\n")
const newlineChar string = "\n"
const messageHeaderSeparator string = " | "
// GetContactByUsername resolves username to user id retrieves user and chat information
func (c *Client) GetContactByUsername(username string) (*client.Chat, *client.User, error) {
if !c.Online() {
return nil, nil, errOffline
}
var chat *client.Chat
var err error
var userID int64
if strings.HasPrefix(username, "@") {
chat, err = c.client.SearchPublicChat(&client.SearchPublicChatRequest{
Username: username,
})
if err != nil {
return nil, nil, err
}
userID = chat.Id
} else {
userID, err = strconv.ParseInt(username, 10, 64)
if err != nil {
return nil, nil, err
}
}
return c.GetContactByID(userID, chat)
}
// GetContactByID gets user and chat information from cache (or tries to retrieve it, if missing)
func (c *Client) GetContactByID(id int64, chat *client.Chat) (*client.Chat, *client.User, error) {
if !c.Online() || id == 0 {
return nil, nil, errOffline
}
var user *client.User
var cacheChat *client.Chat
var ok bool
var err error
user, ok = c.cache.GetUser(id)
if !ok && id > 0 {
user, err = c.client.GetUser(&client.GetUserRequest{
UserId: id,
})
if err == nil {
c.cache.SetUser(id, user)
}
}
cacheChat, ok = c.cache.GetChat(id)
if !ok {
if chat == nil {
cacheChat, err = c.client.GetChat(&client.GetChatRequest{
ChatId: id,
})
if err != nil {
// error is irrelevant if the user was found successfully
if user != nil {
return nil, user, nil
}
return nil, nil, err
}
c.cache.SetChat(id, cacheChat)
} else {
c.cache.SetChat(id, chat)
}
}
if chat == nil {
chat = cacheChat
}
return chat, user, nil
}
// IsPM checks if a chat is PM
func (c *Client) IsPM(id int64) (bool, error) {
if !c.Online() || id == 0 {
return false, errOffline
}
var err error
chat, ok := c.cache.GetChat(id)
if !ok {
chat, err = c.client.GetChat(&client.GetChatRequest{
ChatId: id,
})
if err != nil {
return false, err
}
c.cache.SetChat(id, chat)
}
chatType := chat.Type.ChatTypeType()
if chatType == client.TypeChatTypePrivate || chatType == client.TypeChatTypeSecret {
return true, nil
}
return false, nil
}
func (c *Client) userStatusToText(status client.UserStatus, chatID int64) (string, string, string) {
var show, textStatus, presenceType string
switch status.UserStatusType() {
case client.TypeUserStatusOnline:
onlineStatus, _ := status.(*client.UserStatusOnline)
c.DelayedStatusesLock.Lock()
c.DelayedStatuses[chatID] = &DelayedStatus{
TimestampOnline: time.Now().Unix(),
TimestampExpired: int64(onlineStatus.Expires),
}
c.DelayedStatusesLock.Unlock()
textStatus = "Online"
case client.TypeUserStatusRecently:
show, textStatus = "dnd", "Last seen recently"
c.DelayedStatusesLock.Lock()
delete(c.DelayedStatuses, chatID)
c.DelayedStatusesLock.Unlock()
case client.TypeUserStatusLastWeek:
show, textStatus = "xa", "Last seen last week"
case client.TypeUserStatusLastMonth:
show, textStatus = "xa", "Last seen last month"
case client.TypeUserStatusEmpty:
presenceType, textStatus = "unavailable", "Last seen a long time ago"
case client.TypeUserStatusOffline:
offlineStatus, _ := status.(*client.UserStatusOffline)
// this will stop working in 2038 O\
wasOnline := int64(offlineStatus.WasOnline)
elapsed := time.Now().Unix() - wasOnline
if elapsed < 3600 {
show = "away"
} else {
show = "xa"
}
textStatus = c.LastSeenStatus(wasOnline)
c.DelayedStatusesLock.Lock()
delete(c.DelayedStatuses, chatID)
c.DelayedStatusesLock.Unlock()
}
return show, textStatus, presenceType
}
// LastSeenStatus formats a timestamp to a "Last seen at" string
func (c *Client) LastSeenStatus(timestamp int64) string {
return time.Unix(int64(timestamp), 0).
In(c.Session.TimezoneToLocation()).
Format("Last seen at 15:04 02/01/2006")
}
// ProcessStatusUpdate sets contact status
func (c *Client) ProcessStatusUpdate(chatID int64, status string, show string, oldArgs ...args.V) error {
if !c.Online() {
return nil
}
log.WithFields(log.Fields{
"chat_id": chatID,
}).Info("Status update for")
chat, user, err := c.GetContactByID(chatID, nil)
if err != nil {
return err
}
var photo string
if chat != nil && chat.Photo != nil {
file, path, err := c.ForceOpenFile(chat.Photo.Small, 1)
if err == nil {
defer file.Close()
hash := sha1.New()
_, err = io.Copy(hash, file)
if err == nil {
photo = fmt.Sprintf("%x", hash.Sum(nil))
} else {
log.Errorf("Error calculating hash: %v", path)
}
} else if path != "" {
log.Errorf("Photo does not exist: %v", path)
}
}
var presenceType string
if gateway.SPType.IsSet(oldArgs) {
presenceType = gateway.SPType.Get(oldArgs)
}
cachedStatus, ok := c.cache.GetStatus(chatID)
if status == "" {
if ok {
show, status = cachedStatus.XMPP, cachedStatus.Description
} else if user != nil && user.Status != nil {
show, status, presenceType = c.userStatusToText(user.Status, chatID)
} else {
show, status = "chat", chat.Title
}
}
c.cache.SetStatus(chatID, show, status)
newArgs := []args.V{
gateway.SPFrom(strconv.FormatInt(chatID, 10)),
gateway.SPShow(show),
gateway.SPStatus(status),
gateway.SPPhoto(photo),
gateway.SPResource(gateway.Jid.Resource),
gateway.SPImmed(gateway.SPImmed.Get(oldArgs)),
}
if presenceType != "" {
newArgs = append(newArgs, gateway.SPType(presenceType))
}
return gateway.SendPresence(
c.xmpp,
c.jid,
newArgs...,
)
}
func (c *Client) formatContact(chatID int64) string {
if chatID == 0 {
return ""
}
chat, user, err := c.GetContactByID(chatID, nil)
if err != nil {
return "unknown contact: " + err.Error()
}
var str string
if chat != nil {
str = fmt.Sprintf("%s (%v)", chat.Title, chat.Id)
} else if user != nil {
username := user.Username
if username == "" {
username = strconv.FormatInt(user.Id, 10)
}
str = fmt.Sprintf("%s %s (%v)", user.FirstName, user.LastName, username)
} else {
str = strconv.FormatInt(chatID, 10)
}
str = spaceRegex.ReplaceAllString(str, " ")
return str
}
func (c *Client) getSenderId(message *client.Message) (senderId int64) {
if message.SenderId != nil {
switch message.SenderId.MessageSenderType() {
case client.TypeMessageSenderUser:
senderUser, _ := message.SenderId.(*client.MessageSenderUser)
senderId = senderUser.UserId
case client.TypeMessageSenderChat:
senderChat, _ := message.SenderId.(*client.MessageSenderChat)
senderId = senderChat.ChatId
}
}
return
}
func (c *Client) formatSender(message *client.Message) string {
return c.formatContact(c.getSenderId(message))
}
func (c *Client) getMessageReply(message *client.Message) (reply *gateway.Reply, replyMsg *client.Message) {
if message.ReplyToMessageId != 0 {
var err error
replyMsg, err = c.client.GetMessage(&client.GetMessageRequest{
ChatId: message.ChatId,
MessageId: message.ReplyToMessageId,
})
if err != nil {
log.Errorf("<error fetching message: %s>", err.Error())
return
}
replyId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, message.ChatId, message.ReplyToMessageId)
if err != nil {
replyId = strconv.FormatInt(message.ReplyToMessageId, 10)
}
reply = &gateway.Reply{
Author: fmt.Sprintf("%v@%s", c.getSenderId(replyMsg), gateway.Jid.Full()),
Id: replyId,
}
}
return
}
func (c *Client) formatMessage(chatID int64, messageID int64, preview bool, message *client.Message) string {
var err error
if message == nil {
message, err = c.client.GetMessage(&client.GetMessageRequest{
ChatId: chatID,
MessageId: messageID,
})
if err != nil {
return fmt.Sprintf("<error fetching message: %s>", err.Error())
}
}
if message == nil {
return ""
}
var str strings.Builder
// add messageid and sender
str.WriteString(fmt.Sprintf("%v | %s | ", message.Id, c.formatSender(message)))
// add date
if !preview {
str.WriteString(
time.Unix(int64(message.Date), 0).
In(c.Session.TimezoneToLocation()).
Format("02 Jan 2006 15:04:05 | "),
)
}
// text message
var text string
if message.Content != nil {
text = c.messageToText(message, preview)
}
if text != "" {
if !preview {
str.WriteString(text)
} else {
newlinePos := strings.Index(text, newlineChar)
if newlinePos == -1 {
str.WriteString(text)
} else {
str.WriteString(text[0:newlinePos])
}
}
}
return str.String()
}
func (c *Client) formatForward(fwd *client.MessageForwardInfo) string {
switch fwd.Origin.MessageForwardOriginType() {
case client.TypeMessageForwardOriginUser:
originUser := fwd.Origin.(*client.MessageForwardOriginUser)
return c.formatContact(originUser.SenderUserId)
case client.TypeMessageForwardOriginChat:
originChat := fwd.Origin.(*client.MessageForwardOriginChat)
var signature string
if originChat.AuthorSignature != "" {
signature = fmt.Sprintf(" (%s)", originChat.AuthorSignature)
}
return c.formatContact(originChat.SenderChatId) + signature
case client.TypeMessageForwardOriginHiddenUser:
originUser := fwd.Origin.(*client.MessageForwardOriginHiddenUser)
return originUser.SenderName
case client.TypeMessageForwardOriginChannel:
channel := fwd.Origin.(*client.MessageForwardOriginChannel)
var signature string
if channel.AuthorSignature != "" {
signature = fmt.Sprintf(" (%s)", channel.AuthorSignature)
}
return c.formatContact(channel.ChatId) + signature
case client.TypeMessageForwardOriginMessageImport:
originImport := fwd.Origin.(*client.MessageForwardOriginMessageImport)
return originImport.SenderName
}
return "Unknown forward type"
}
func (c *Client) formatFile(file *client.File, compact bool) (string, string) {
if file == nil {
return "", ""
}
src, link := c.PermastoreFile(file, false)
if compact {
return link, link
} else {
return fmt.Sprintf("%s (%v kbytes) | %s", filepath.Base(src), file.Size/1024, link), link
}
}
// PermastoreFile steals a file out of TDlib control into an independent shared directory
func (c *Client) PermastoreFile(file *client.File, clone bool) (string, string) {
log.Debugf("file: %#v", file)
if file == nil || file.Local == nil || file.Remote == nil {
return "", ""
}
gateway.StorageLock.Lock()
defer gateway.StorageLock.Unlock()
var link string
var src string
if c.content.Path != "" && c.content.Link != "" {
src = file.Local.Path // source path
_, err := os.Stat(src)
if err != nil {
log.Errorf("Cannot access source file: %v", err)
return "", ""
}
size64 := uint64(file.Size)
c.prepareDiskSpace(size64)
basename := file.Remote.UniqueId + filepath.Ext(src)
dest := c.content.Path + "/" + basename // destination path
link = c.content.Link + "/" + basename // download link
if clone {
file, path, err := c.ForceOpenFile(file, 1)
if err == nil {
defer file.Close()
// mode
mode := os.FileMode(0644)
fi, err := os.Stat(path)
if err == nil {
mode = fi.Mode().Perm()
}
// create destination
tempFile, err := os.OpenFile(dest, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
if err != nil {
pathErr := err.(*os.PathError)
if pathErr.Err.Error() == "file exists" {
log.Warn(err.Error())
return src, link
} else {
log.Errorf("File creation error: %v", err)
return "<ERROR>", ""
}
}
defer tempFile.Close()
// copy
_, err = io.Copy(tempFile, file)
if err != nil {
log.Errorf("File copying error: %v", err)
return "<ERROR>", ""
}
} else if path != "" {
log.Errorf("Source file does not exist: %v", path)
return "<ERROR>", ""
} else {
log.Errorf("PHOTO: %#v", err.Error())
return "<ERROR>", ""
}
} else {
// move
err = os.Rename(src, dest)
if err != nil {
linkErr := err.(*os.LinkError)
if linkErr.Err.Error() == "file exists" {
log.Warn(err.Error())
} else {
log.Errorf("File moving error: %v", err)
return "<ERROR>", ""
}
}
}
// chown
if c.content.User != "" {
user, err := osUser.Lookup(c.content.User)
if err == nil {
uid, err := strconv.ParseInt(user.Uid, 10, 0)
if err == nil {
err = os.Chown(dest, int(uid), -1)
if err != nil {
log.Errorf("Chown error: %v", err)
}
} else {
log.Errorf("Broken uid: %v", err)
}
} else {
log.Errorf("Wrong user name for chown: %v", err)
}
}
// copy or move should have succeeded at this point
gateway.CachedStorageSize += size64
}
return src, link
}
func (c *Client) formatBantime(hours int64) int32 {
var until int32
if hours > 0 {
until = int32(time.Now().Unix() + hours*3600)
}
return until
}
func (c *Client) formatLocation(location *client.Location) string {
return fmt.Sprintf(
"coordinates: %v,%v | https://www.google.com/maps/search/%v,%v/",
location.Latitude,
location.Longitude,
location.Latitude,
location.Longitude,
)
}
func (c *Client) messageToText(message *client.Message, preview bool) string {
if message.Content == nil {
log.Warnf("Unknown message: %#v", message)
return "<empty message>"
}
markupFunction := formatter.EntityToXEP0393
switch message.Content.MessageContentType() {
case client.TypeMessageSticker:
sticker, _ := message.Content.(*client.MessageSticker)
return sticker.Sticker.Emoji
case client.TypeMessageAnimatedEmoji:
animatedEmoji, _ := message.Content.(*client.MessageAnimatedEmoji)
return animatedEmoji.Emoji
case client.TypeMessageBasicGroupChatCreate, client.TypeMessageSupergroupChatCreate:
return "has created chat"
case client.TypeMessageChatJoinByLink:
return "joined chat via invite link"
case client.TypeMessageChatAddMembers:
addMembers, _ := message.Content.(*client.MessageChatAddMembers)
text := "invited "
if len(addMembers.MemberUserIds) > 0 {
text += c.formatContact(addMembers.MemberUserIds[0])
}
return text
case client.TypeMessageChatDeleteMember:
deleteMember, _ := message.Content.(*client.MessageChatDeleteMember)
return "kicked " + c.formatContact(deleteMember.UserId)
case client.TypeMessagePinMessage:
pinMessage, _ := message.Content.(*client.MessagePinMessage)
return "pinned message: " + c.formatMessage(message.ChatId, pinMessage.MessageId, preview, nil)
case client.TypeMessageChatChangeTitle:
changeTitle, _ := message.Content.(*client.MessageChatChangeTitle)
return "chat title set to: " + changeTitle.Title
case client.TypeMessageLocation:
location, _ := message.Content.(*client.MessageLocation)
return c.formatLocation(location.Location)
case client.TypeMessageVenue:
venue, _ := message.Content.(*client.MessageVenue)
if preview {
return venue.Venue.Title
} else {
return fmt.Sprintf(
"*%s*\n%s\n%s",
venue.Venue.Title,
venue.Venue.Address,
c.formatLocation(venue.Venue.Location),
)
}
case client.TypeMessagePhoto:
photo, _ := message.Content.(*client.MessagePhoto)
if preview {
return photo.Caption.Text
} else {
return formatter.Format(
photo.Caption.Text,
photo.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageAudio:
audio, _ := message.Content.(*client.MessageAudio)
if preview {
return audio.Caption.Text
} else {
return formatter.Format(
audio.Caption.Text,
audio.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageVideo:
video, _ := message.Content.(*client.MessageVideo)
if preview {
return video.Caption.Text
} else {
return formatter.Format(
video.Caption.Text,
video.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageDocument:
document, _ := message.Content.(*client.MessageDocument)
if preview {
return document.Caption.Text
} else {
return formatter.Format(
document.Caption.Text,
document.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageText:
text, _ := message.Content.(*client.MessageText)
if preview {
return text.Text.Text
} else {
return formatter.Format(
text.Text.Text,
text.Text.Entities,
markupFunction,
)
}
case client.TypeMessageVoiceNote:
voice, _ := message.Content.(*client.MessageVoiceNote)
if preview {
return voice.Caption.Text
} else {
return formatter.Format(
voice.Caption.Text,
voice.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageVideoNote:
return ""
case client.TypeMessageAnimation:
animation, _ := message.Content.(*client.MessageAnimation)
if preview {
return animation.Caption.Text
} else {
return formatter.Format(
animation.Caption.Text,
animation.Caption.Entities,
markupFunction,
)
}
case client.TypeMessageContact:
contact, _ := message.Content.(*client.MessageContact)
if preview {
return contact.Contact.FirstName + " " + contact.Contact.LastName
} else {
var jid string
if contact.Contact.UserId != 0 {
jid = fmt.Sprintf("%v@%s", contact.Contact.UserId, gateway.Jid.Bare())
}
return fmt.Sprintf(
"*%s %s*\n%s\n%s\n%s",
contact.Contact.FirstName,
contact.Contact.LastName,
contact.Contact.PhoneNumber,
contact.Contact.Vcard,
jid,
)
}
case client.TypeMessageDice:
dice, _ := message.Content.(*client.MessageDice)
return fmt.Sprintf("%s 1d6: [%v]", dice.Emoji, dice.Value)
case client.TypeMessagePoll:
poll, _ := message.Content.(*client.MessagePoll)
if preview {
return poll.Poll.Question
} else {
rows := []string{}
rows = append(rows, fmt.Sprintf("*%s*", poll.Poll.Question))
for _, option := range poll.Poll.Options {
var tick string
if option.IsChosen {
tick = "x"
} else {
tick = " "
}
rows = append(rows, fmt.Sprintf(
"[%s] %s | %v%% | %v vote",
tick,
option.Text,
option.VotePercentage,
option.VoterCount,
))
}
return strings.Join(rows, "\n")
}
}
return fmt.Sprintf("unknown message (%s)", message.Content.MessageContentType())
}
func (c *Client) contentToFile(content client.MessageContent) (*client.File, *client.File) {
if content == nil {
return nil, nil
}
switch content.MessageContentType() {
case client.TypeMessageSticker:
sticker, _ := content.(*client.MessageSticker)
file := sticker.Sticker.Sticker
if sticker.Sticker.IsAnimated && sticker.Sticker.Thumbnail != nil && sticker.Sticker.Thumbnail.File != nil {
file = sticker.Sticker.Thumbnail.File
}
return file, nil
case client.TypeMessageVoiceNote:
voice, _ := content.(*client.MessageVoiceNote)
return voice.VoiceNote.Voice, nil
case client.TypeMessageVideoNote:
video, _ := content.(*client.MessageVideoNote)
var preview *client.File
if video.VideoNote.Thumbnail != nil {
preview = video.VideoNote.Thumbnail.File
}
return video.VideoNote.Video, preview
case client.TypeMessageAnimation:
animation, _ := content.(*client.MessageAnimation)
var preview *client.File
if animation.Animation.Thumbnail != nil {
preview = animation.Animation.Thumbnail.File
}
return animation.Animation.Animation, preview
case client.TypeMessagePhoto:
photo, _ := content.(*client.MessagePhoto)
sizes := photo.Photo.Sizes
if len(sizes) >= 1 {
file := sizes[len(sizes)-1].Photo
return file, nil
}
return nil, nil
case client.TypeMessageAudio:
audio, _ := content.(*client.MessageAudio)
var preview *client.File
if audio.Audio.AlbumCoverThumbnail != nil {
preview = audio.Audio.AlbumCoverThumbnail.File
}
return audio.Audio.Audio, preview
case client.TypeMessageVideo:
video, _ := content.(*client.MessageVideo)
var preview *client.File
if video.Video.Thumbnail != nil {
preview = video.Video.Thumbnail.File
}
return video.Video.Video, preview
case client.TypeMessageDocument:
document, _ := content.(*client.MessageDocument)
var preview *client.File
if document.Document.Thumbnail != nil {
preview = document.Document.Thumbnail.File
}
return document.Document.Document, preview
}
return nil, nil
}
func (c *Client) countCharsInLines(lines *[]string) (count int) {
for _, line := range *lines {
count += len(line)
}
return
}
func (c *Client) messageToPrefix(message *client.Message, previewString string, fileString string, replyMsg *client.Message) (string, int, int) {
isPM, err := c.IsPM(message.ChatId)
if err != nil {
log.Errorf("Could not determine if chat is PM: %v", err)
}
var replyStart, replyEnd int
prefix := []string{}
// message direction
var directionChar string
if !isPM || !gateway.MessageOutgoingPermission || !c.Session.Carbons {
if c.Session.AsciiArrows {
if message.IsOutgoing {
directionChar = "> "
} else {
directionChar = "< "
}
} else {
if message.IsOutgoing {
directionChar = "➡ "
} else {
directionChar = "⬅ "
}
}
}
if !isPM || !c.Session.HideIds {
prefix = append(prefix, directionChar+strconv.FormatInt(message.Id, 10))
}
// show sender in group chats
if !isPM {
sender := c.formatSender(message)
if sender != "" {
prefix = append(prefix, sender)
}
}
// reply to
if message.ReplyToMessageId != 0 {
if len(prefix) > 0 {
replyStart = c.countCharsInLines(&prefix) + (len(prefix)-1)*len(messageHeaderSeparator)
}
replyLine := "reply: " + c.formatMessage(message.ChatId, message.ReplyToMessageId, true, replyMsg)
prefix = append(prefix, replyLine)
replyEnd = replyStart + len(replyLine)
if len(prefix) > 0 {
replyEnd += len(messageHeaderSeparator)
}
}
if message.ForwardInfo != nil {
prefix = append(prefix, "fwd: "+c.formatForward(message.ForwardInfo))
}
// preview
if previewString != "" {
prefix = append(prefix, "preview: "+previewString)
}
// file
if fileString != "" {
prefix = append(prefix, "file: "+fileString)
}
return strings.Join(prefix, messageHeaderSeparator), replyStart, replyEnd
}
func (c *Client) ensureDownloadFile(file *client.File) *client.File {
gateway.StorageLock.Lock()
defer gateway.StorageLock.Unlock()
if file != nil {
c.prepareDiskSpace(uint64(file.Size))
newFile, err := c.DownloadFile(file.Id, 1, true)
if err == nil {
return newFile
}
}
return file
}
// ProcessIncomingMessage transfers a message to XMPP side and marks it as read on Telegram side
func (c *Client) ProcessIncomingMessage(chatId int64, message *client.Message) {
var text, oob, auxText string
var err error
reply, replyMsg := c.getMessageReply(message)
content := message.Content
if content != nil && content.MessageContentType() == client.TypeMessageChatChangePhoto {
chat, err := c.client.GetChat(&client.GetChatRequest{
ChatId: chatId,
})
if err == nil {
c.cache.SetChat(chatId, chat)
go c.ProcessStatusUpdate(chatId, "", "", gateway.SPImmed(true))
text = "<Chat photo has changed>"
}
} else {
text = c.messageToText(message, false)
// OTR support (I do not know why would you need it, seriously)
if !(strings.HasPrefix(text, "?OTR") || (c.Session.RawMessages && !c.Session.OOBMode)) {
file, preview := c.contentToFile(content)
// download file and preview (if present)
file = c.ensureDownloadFile(file)
preview = c.ensureDownloadFile(preview)
previewName, _ := c.formatFile(preview, true)
fileName, link := c.formatFile(file, false)
oob = link
if c.Session.OOBMode && oob != "" {
typ := message.Content.MessageContentType()
if typ != client.TypeMessageSticker {
auxText = text
}
text = oob
} else if !c.Session.RawMessages {
var newText strings.Builder
prefix, replyStart, replyEnd := c.messageToPrefix(message, previewName, fileName, replyMsg)
newText.WriteString(prefix)
if reply != nil {
reply.Start = uint64(replyStart)
reply.End = uint64(replyEnd)
}
if text != "" {
// \n if it is groupchat and message is not empty
if prefix != "" {
if chatId < 0 {
newText.WriteString("\n")
} else if chatId > 0 {
newText.WriteString(" | ")
}
}
newText.WriteString(text)
}
text = newText.String()
}
}
}
// mark message as read
c.client.ViewMessages(&client.ViewMessagesRequest{
ChatId: chatId,
MessageIds: []int64{message.Id},
ForceRead: true,
})
// forward message to XMPP
sId := strconv.FormatInt(message.Id, 10)
sChatId := strconv.FormatInt(chatId, 10)
var jids []string
var isPM bool
if gateway.MessageOutgoingPermission && c.Session.Carbons {
isPM, err = c.IsPM(chatId)
if err != nil {
log.Errorf("Could not determine if chat is PM: %v", err)
}
}
isOutgoing := isPM && message.IsOutgoing
if isOutgoing {
for resource := range c.resourcesRange() {
jids = append(jids, c.jid+"/"+resource)
}
} else {
jids = []string{c.jid}
}
for _, jid := range jids {
gateway.SendMessageWithOOB(jid, sChatId, text, sId, c.xmpp, reply, oob, isOutgoing)
if auxText != "" {
gateway.SendMessage(jid, sChatId, auxText, sId, c.xmpp, reply, isOutgoing)
}
}
}
// PrepareMessageContent creates a simple text message
func (c *Client) PrepareOutgoingMessageContent(text string) client.InputMessageContent {
return c.prepareOutgoingMessageContent(text, nil)
}
// ProcessOutgoingMessage executes commands or sends messages to mapped chats, returns message id
func (c *Client) ProcessOutgoingMessage(chatID int64, text string, returnJid string, replyId int64, replaceId int64) int64 {
if !c.Online() {
// we're offline
return 0
}
if replaceId == 0 && (strings.HasPrefix(text, "/") || strings.HasPrefix(text, "!")) {
// try to execute commands
response, isCommand := c.ProcessChatCommand(chatID, text)
if response != "" {
c.returnMessage(returnJid, chatID, response)
}
// do not send on success
if isCommand {
return 0
}
}
log.Warnf("Sending message to chat %v", chatID)
// quotations
var reply int64
if replaceId == 0 && replyId == 0 {
replySlice := replyRegex.FindStringSubmatch(text)
if len(replySlice) > 1 {
reply, _ = strconv.ParseInt(replySlice[1], 10, 64)
}
} else {
reply = replyId
}
// attach a file
var file *client.InputFileLocal
if c.content.Upload != "" && strings.HasPrefix(text, c.content.Upload) {
response, err := http.Get(text)
if err != nil {
c.returnError(returnJid, chatID, "Failed to fetch the uploaded file", err)
}
if response != nil && response.Body != nil {
defer response.Body.Close()
if response.StatusCode != 200 {
c.returnMessage(returnJid, chatID, fmt.Sprintf("Received status code %v", response.StatusCode))
}
tempDir, err := ioutil.TempDir("", "telegabber-*")
if err != nil {
c.returnError(returnJid, chatID, "Failed to create a temporary directory", err)
}
tempFile, err := os.Create(filepath.Join(tempDir, filepath.Base(text)))
if err != nil {
c.returnError(returnJid, chatID, "Failed to create a temporary file", err)
}
_, err = io.Copy(tempFile, response.Body)
if err != nil {
c.returnError(returnJid, chatID, "Failed to write a temporary file", err)
}
file = &client.InputFileLocal{
Path: tempFile.Name(),
}
}
}
// remove first line from text
if file != nil || (reply != 0 && replyId == 0) {
newlinePos := strings.Index(text, newlineChar)
if newlinePos != -1 {
text = text[newlinePos+1:]
} else {
text = ""
}
}
content := c.prepareOutgoingMessageContent(text, file)
if replaceId != 0 {
tgMessage, err := c.client.EditMessageText(&client.EditMessageTextRequest{
ChatId: chatID,
MessageId: replaceId,
InputMessageContent: content,
})
if err != nil {
c.returnError(returnJid, chatID, "Not edited", err)
return 0
}
return tgMessage.Id
}
tgMessage, err := c.client.SendMessage(&client.SendMessageRequest{
ChatId: chatID,
ReplyToMessageId: reply,
InputMessageContent: content,
})
if err != nil {
c.returnError(returnJid, chatID, "Not sent", err)
return 0
}
return tgMessage.Id
}
func (c *Client) returnMessage(returnJid string, chatID int64, text string) {
gateway.SendTextMessage(returnJid, strconv.FormatInt(chatID, 10), text, c.xmpp)
}
func (c *Client) returnError(returnJid string, chatID int64, msg string, err error) {
c.returnMessage(returnJid, chatID, fmt.Sprintf("%s: %s", msg, err.Error()))
}
func (c *Client) prepareOutgoingMessageContent(text string, file *client.InputFileLocal) client.InputMessageContent {
formattedText := &client.FormattedText{
Text: text,
}
var content client.InputMessageContent
if file != nil {
// we can try to send a document
content = &client.InputMessageDocument{
Document: file,
Caption: formattedText,
}
} else {
// compile our message
content = &client.InputMessageText{
Text: formattedText,
}
}
return content
}
// StatusesRange proxies the following function from unexported cache
func (c *Client) StatusesRange() chan *cache.Status {
return c.cache.StatusesRange()
}
func (c *Client) addResource(resource string) {
if resource == "" {
return
}
c.locks.resourcesLock.Lock()
defer c.locks.resourcesLock.Unlock()
c.resources[resource] = true
}
func (c *Client) deleteResource(resource string) {
c.locks.resourcesLock.Lock()
defer c.locks.resourcesLock.Unlock()
if _, ok := c.resources[resource]; ok {
delete(c.resources, resource)
}
}
func (c *Client) resourcesRange() chan string {
c.locks.resourcesLock.Lock()
resourceChan := make(chan string, 1)
go func() {
defer func() {
c.locks.resourcesLock.Unlock()
close(resourceChan)
}()
for resource := range c.resources {
resourceChan <- resource
}
}()
return resourceChan
}
// resend statuses to (to another resource, for example)
func (c *Client) roster(resource string) {
if _, ok := c.resources[resource]; ok {
return // we know it
}
log.Warnf("Sending roster for %v", resource)
for _, chat := range c.cache.ChatsKeys() {
c.ProcessStatusUpdate(chat, "", "")
}
gateway.SendPresence(c.xmpp, c.jid, gateway.SPStatus("Logged in as: "+c.Session.Login))
c.addResource(resource)
}
// get last messages from specified chat
func (c *Client) getLastMessages(id int64, query string, from int64, count int32) (*client.Messages, error) {
return c.client.SearchChatMessages(&client.SearchChatMessagesRequest{
ChatId: id,
Query: query,
SenderId: &client.MessageSenderUser{UserId: from},
Filter: &client.SearchMessagesFilterEmpty{},
Limit: count,
})
}
// DownloadFile actually obtains a file by id given by TDlib
func (c *Client) DownloadFile(id int32, priority int32, synchronous bool) (*client.File, error) {
return c.client.DownloadFile(&client.DownloadFileRequest{
FileId: id,
Priority: priority,
Synchronous: synchronous,
})
}
// ForceOpenFile reliably obtains a file if possible
func (c *Client) ForceOpenFile(tgFile *client.File, priority int32) (*os.File, string, error) {
if tgFile == nil {
return nil, "", errors.New("File not found")
}
path := tgFile.Local.Path
file, err := os.Open(path)
if err == nil {
return file, path, nil
} else
// obtain the photo right now if still not downloaded
if !tgFile.Local.IsDownloadingCompleted {
tdFile, tdErr := c.DownloadFile(tgFile.Id, priority, true)
if tdErr == nil {
path = tdFile.Local.Path
file, err = os.Open(path)
return file, path, err
}
}
// give up
return nil, path, err
}
// GetChatDescription obtains bio or description according to the chat type
func (c *Client) GetChatDescription(chat *client.Chat) string {
chatType := chat.Type.ChatTypeType()
if chatType == client.TypeChatTypePrivate {
privateType, _ := chat.Type.(*client.ChatTypePrivate)
fullInfo, err := c.client.GetUserFullInfo(&client.GetUserFullInfoRequest{
UserId: privateType.UserId,
})
if err == nil {
if fullInfo.Bio != "" {
return fullInfo.Bio
} else if fullInfo.Description != "" {
return fullInfo.Description
}
} else {
log.Warnf("Coudln't retrieve private chat info: %v", err.Error())
}
} else if chatType == client.TypeChatTypeBasicGroup {
basicGroupType, _ := chat.Type.(*client.ChatTypeBasicGroup)
fullInfo, err := c.client.GetBasicGroupFullInfo(&client.GetBasicGroupFullInfoRequest{
BasicGroupId: basicGroupType.BasicGroupId,
})
if err == nil {
return fullInfo.Description
} else {
log.Warnf("Coudln't retrieve basic group info: %v", err.Error())
}
} else if chatType == client.TypeChatTypeSupergroup {
supergroupType, _ := chat.Type.(*client.ChatTypeSupergroup)
fullInfo, err := c.client.GetSupergroupFullInfo(&client.GetSupergroupFullInfoRequest{
SupergroupId: supergroupType.SupergroupId,
})
if err == nil {
return fullInfo.Description
} else {
log.Warnf("Coudln't retrieve supergroup info: %v", err.Error())
}
}
return ""
}
// subscribe to a Telegram ID
func (c *Client) subscribeToID(id int64, chat *client.Chat) {
var args []args.V
args = append(args, gateway.SPFrom(strconv.FormatInt(id, 10)))
args = append(args, gateway.SPType("subscribe"))
if chat == nil {
chat, _, _ = c.GetContactByID(id, nil)
}
if chat != nil {
args = append(args, gateway.SPNickname(chat.Title))
gateway.SetNickname(c.jid, strconv.FormatInt(id, 10), chat.Title, c.xmpp)
}
gateway.SendPresence(
c.xmpp,
c.jid,
args...,
)
}
func (c *Client) prepareDiskSpace(size uint64) {
if gateway.StorageQuota > 0 && c.content.Path != "" {
var loweredQuota uint64
if gateway.StorageQuota >= size {
loweredQuota = gateway.StorageQuota - size
}
if gateway.CachedStorageSize >= loweredQuota {
log.Warn("Storage is rapidly clogged")
gateway.CleanOldFiles(c.content.Path, loweredQuota)
}
}
}
func (c *Client) GetVcardInfo(toID int64) (VCardInfo, error) {
var info VCardInfo
chat, user, err := c.GetContactByID(toID, nil)
if err != nil {
return info, err
}
if chat != nil {
info.Fn = chat.Title
if chat.Photo != nil {
info.Photo = chat.Photo.Small
}
info.Info = c.GetChatDescription(chat)
}
if user != nil {
info.Nickname = user.Username
info.Given = user.FirstName
info.Family = user.LastName
info.Tel = user.PhoneNumber
}
return info, nil
}
|