-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathportal.go
2461 lines (2262 loc) · 77.2 KB
/
portal.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 main
import (
"bytes"
"github.com/gabriel-vasile/mimetype"
"maunium.net/go/mautrix/patch"
"encoding/hex"
"encoding/xml"
"fmt"
"html"
"image"
"image/gif"
"image/jpeg"
"image/png"
"math/rand"
"net/http"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
skype "github.com/kelaresg/go-skypeapi"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"github.com/pkg/errors"
log "maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/crypto/attachment"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/pushrules"
"github.com/kelaresg/matrix-skype/database"
"github.com/kelaresg/matrix-skype/types"
)
func (bridge *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
portal, ok := bridge.portalsByMXID[mxid]
if !ok {
fmt.Println("loadDBPortal1")
return bridge.loadDBPortal(bridge.DB.Portal.GetByMXID(mxid), nil)
}
return portal
}
func (bridge *Bridge) GetPortalByJID(key database.PortalKey) *Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
portal, ok := bridge.portalsByJID[key]
if !ok {
fmt.Println("loadDBPortal2")
return bridge.loadDBPortal(bridge.DB.Portal.GetByJID(key), &key)
}
return portal
}
func (bridge *Bridge) GetAllPortals() []*Portal {
return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAll())
}
func (bridge *Bridge) GetAllPortalsByJID(jid types.SkypeID) []*Portal {
return bridge.dbPortalsToPortals(bridge.DB.Portal.GetAllByJID(jid))
}
func (bridge *Bridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
bridge.portalsLock.Lock()
defer bridge.portalsLock.Unlock()
output := make([]*Portal, len(dbPortals))
for index, dbPortal := range dbPortals {
if dbPortal == nil {
continue
}
portal, ok := bridge.portalsByJID[dbPortal.Key]
if !ok {
fmt.Println("loadDBPortal3")
portal = bridge.loadDBPortal(dbPortal, nil)
}
output[index] = portal
}
return output
}
func (bridge *Bridge) loadDBPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
fmt.Println("loadDBPortal: ", dbPortal)
if dbPortal == nil {
if key == nil {
return nil
}
dbPortal = bridge.DB.Portal.New()
dbPortal.Key = *key
dbPortal.Insert()
}
portal := bridge.NewPortal(dbPortal)
bridge.portalsByJID[portal.Key] = portal
fmt.Println("loadDBPortal portal.MXID", portal.MXID)
if len(portal.MXID) > 0 {
bridge.portalsByMXID[portal.MXID] = portal
}
return portal
}
func (portal *Portal) GetUsers() []*User {
return nil
}
func (bridge *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
portal := &Portal{
Portal: dbPortal,
bridge: bridge,
log: bridge.Log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
recentlyHandled: [recentlyHandledLength]types.SkypeMessageID{},
messages: make(chan PortalMessage, 128),
}
fmt.Println("NewPortal: ")
go portal.handleMessageLoop()
return portal
}
const recentlyHandledLength = 100
type PortalMessage struct {
chat string
source *User
data interface{}
timestamp uint64
}
type Portal struct {
*database.Portal
bridge *Bridge
log log.Logger
roomCreateLock sync.Mutex
recentlyHandled [recentlyHandledLength]types.SkypeMessageID
recentlyHandledLock sync.Mutex
recentlyHandledIndex uint8
backfillLock sync.Mutex
backfilling bool
lastMessageTs uint64
privateChatBackfillInvitePuppet func()
messages chan PortalMessage
isPrivate *bool
hasRelaybot *bool
}
const MaxMessageAgeToCreatePortal = 5 * 60 // 5 minutes
func (portal *Portal) handleMessageLoop() {
for msg := range portal.messages {
fmt.Println()
fmt.Printf("portal handleMessageLoop: %+v", msg)
if len(portal.MXID) == 0 {
if msg.timestamp+MaxMessageAgeToCreatePortal < uint64(time.Now().Unix()) {
portal.log.Debugln("Not creating portal room for incoming message as the message is too old.")
continue
}
portal.log.Debugln("Creating Matrix room from incoming message")
err := portal.CreateMatrixRoom(msg.source)
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
fmt.Println()
fmt.Printf("portal handleMessageLoop2: %+v", msg)
return
}
} else {
if !msg.source.IsInPortal(portal.Key) {
fmt.Println("portal handleMessageLoop InPortal:")
msg.source.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: false})
}
}
fmt.Println()
fmt.Printf("portal handleMessageLoop3: %+v", msg)
portal.backfillLock.Lock()
portal.handleMessage(msg)
portal.backfillLock.Unlock()
}
}
func (portal *Portal) handleMessage(msg PortalMessage) {
fmt.Println()
fmt.Printf("portal handleMessage: %+v", msg)
if len(portal.MXID) == 0 {
portal.log.Warnln("handleMessage called even though portal.MXID is empty")
return
}
data, ok := msg.data.(skype.Resource)
if ok {
switch data.MessageType {
case "RichText", "Text":
portal.HandleTextMessage(msg.source, data)
case "RichText/UriObject":
//portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, 0, false)
portal.HandleMediaMessageSkype(msg.source, data.Download, data.MessageType, nil, data, false)
case "RichText/Media_Video":
//portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, 0, false)
portal.HandleMediaMessageSkype(msg.source, data.Download, data.MessageType, nil, data, false)
case "RichText/Media_AudioMsg":
//portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, 0, false)
portal.HandleMediaMessageSkype(msg.source, data.Download, data.MessageType, nil, data, false)
case "RichText/Media_GenericFile":
//portal.HandleMediaMessage(msg.source, data.Download, data.Thumbnail, data.Info, data.ContextInfo, data.Type, data.Caption, 0, false)
portal.HandleMediaMessageSkype(msg.source, data.Download, data.MessageType, nil, data, false)
case "RichText/Contacts":
portal.HandleContactMessageSkype(msg.source, data)
case "RichText/Location":
portal.HandleLocationMessageSkype(msg.source, data)
default:
portal.log.Warnln("Unknown message type:", reflect.TypeOf(msg.data))
}
} else {
portal.log.Warnln("Unknown message type:", reflect.TypeOf(msg.data))
}
}
func (portal *Portal) isRecentlyHandled(id types.SkypeMessageID) bool {
start := portal.recentlyHandledIndex
for i := start; i != start; i = (i - 1) % recentlyHandledLength {
if portal.recentlyHandled[i] == id {
return true
}
}
return false
}
func (portal *Portal) isDuplicate(clientMessageId types.SkypeMessageID, id string) bool {
msg := portal.bridge.DB.Message.GetByJID(portal.Key, clientMessageId)
if msg != nil && len(msg.ID) < 1 {
msg.UpdateIDByJID(id)
}
if msg != nil {
return true
}
return false
}
//func init() {
// gob.Register(&waProto.Message{})
//}
//func (portal *Portal) markHandled(source *User, message *waProto.WebMessageInfo, mxid id.EventID) {
// msg := portal.bridge.DB.Message.New()
// msg.Chat = portal.Key
// msg.JID = message.GetKey().GetId()
// msg.MXID = mxid
// msg.Timestamp = message.GetMessageTimestamp()
// if message.GetKey().GetFromMe() {
// msg.Sender = source.JID
// } else if portal.IsPrivateChat() {
// msg.Sender = portal.Key.JID
// } else {
// msg.Sender = message.GetKey().GetParticipant()
// if len(msg.Sender) == 0 {
// msg.Sender = message.GetParticipant()
// }
// }
// //msg.Content = message.Message
// msg.Content = &skype.Resource{}
// msg.Insert()
//
// portal.recentlyHandledLock.Lock()
// index := portal.recentlyHandledIndex
// portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
// portal.recentlyHandledLock.Unlock()
// portal.recentlyHandled[index] = msg.JID
//}
func (portal *Portal) markHandledSkype(source *User, message *skype.Resource, mxid id.EventID) {
msg := portal.bridge.DB.Message.New()
msg.Chat = portal.Key
msg.JID = message.ClientMessageId
msg.MXID = mxid
msg.Timestamp = uint64(message.Timestamp)
if message.GetFromMe(source.Conn.Conn) {
msg.Sender = source.JID
} else if portal.IsPrivateChat() {
msg.Sender = source.JID
} else {
msg.Sender = source.JID
//if len(msg.Sender) == 0 {
// msg.Sender = message.Jid
//}
}
msg.Content = message.Content
if len(message.Id) > 0 {
msg.ID = message.Id
}
msg.Insert()
fmt.Println("markHandledSkype1", msg.Chat.JID)
fmt.Println("markHandledSkype2", msg.JID)
portal.recentlyHandledLock.Lock()
index := portal.recentlyHandledIndex
portal.recentlyHandledIndex = (portal.recentlyHandledIndex + 1) % recentlyHandledLength
portal.recentlyHandledLock.Unlock()
portal.recentlyHandled[index] = msg.JID
}
//func (portal *Portal) getMessageIntent(user *User, info whatsapp.MessageInfo) *appservice.IntentAPI {
// if info.FromMe {
// return portal.bridge.GetPuppetByJID(user.JID).IntentFor(portal)
// } else if portal.IsPrivateChat() {
// return portal.MainIntent()
// } else if len(info.SenderJid) == 0 {
// if len(info.Source.GetParticipant()) != 0 {
// info.SenderJid = info.Source.GetParticipant()
// } else {
// return nil
// }
// }
// return portal.bridge.GetPuppetByJID(info.SenderJid).IntentFor(portal)
//}
func (portal *Portal) getMessageIntentSkype(user *User, info skype.Resource) *appservice.IntentAPI {
if info.GetFromMe(user.Conn.Conn) {
return portal.bridge.GetPuppetByJID(user.JID).IntentFor(portal)
} else if portal.IsPrivateChat() {
return portal.MainIntent()
} else if len(info.SendId) == 0 {
//if len(info.Source.GetParticipant()) != 0 {
// info.SenderJid = info.Source.GetParticipant()
//} else {
// return nil
//}
return nil
}
fmt.Println()
fmt.Println("getMessageIntentSkype")
fmt.Println()
return portal.bridge.GetPuppetByJID(info.SendId + skypeExt.NewUserSuffix).IntentFor(portal)
}
func (portal *Portal) handlePrivateChatFromMe(user *User, fromMe bool) func() {
_, homeserver, _ := user.MXID.Parse()
if portal.IsPrivateChat() && fromMe && len(portal.bridge.Config.Bridge.LoginSharedSecretMap[homeserver]) == 0 {
var privateChatPuppet *Puppet
var privateChatPuppetInvited bool
privateChatPuppet = portal.bridge.GetPuppetByJID(portal.Key.Receiver)
if privateChatPuppetInvited {
return nil
}
privateChatPuppetInvited = true
_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: privateChatPuppet.MXID})
_ = privateChatPuppet.DefaultIntent().EnsureJoined(portal.MXID)
return func() {
if privateChatPuppet != nil && privateChatPuppetInvited {
//_, _ = privateChatPuppet.DefaultIntent().LeaveRoom(portal.MXID)
}
}
}
return nil
}
func (portal *Portal) startHandlingSkype(source *User, info skype.Resource) (*appservice.IntentAPI, func()) {
// TODO these should all be trace logs
if portal.lastMessageTs > uint64(info.Timestamp)+1 {
portal.log.Debugfln("Not handling %s: message is older (%d) than last bridge message (%d)", info.Id, info.Timestamp, portal.lastMessageTs)
} else if portal.isRecentlyHandled(info.Id) {
portal.log.Debugfln("Not handling %s: message was recently handled", info.Id)
} else if portal.isDuplicate(info.ClientMessageId, info.Id) {
portal.log.Debugfln("Not handling %s: message is duplicate", info.ClientMessageId)
} else {
portal.log.Debugfln("Starting handling of %s (ts: %d)", info.Id, info.Timestamp)
portal.lastMessageTs = uint64(info.Timestamp)
return portal.getMessageIntentSkype(source, info), portal.handlePrivateChatFromMe(source, info.GetFromMe(source.Conn.Conn))
}
portal.log.Debugfln("startHandlingSkype: %+v", "but nil")
return nil, nil
}
//func (portal *Portal) finishHandling(source *User, message *waProto.WebMessageInfo, mxid id.EventID) {
// portal.markHandled(source, message, mxid)
// portal.sendDeliveryReceipt(mxid)
// portal.log.Debugln("Handled message", message.GetKey().GetId(), "->", mxid)
//}
func (portal *Portal) finishHandlingSkype(source *User, message *skype.Resource, mxid id.EventID) {
portal.markHandledSkype(source, message, mxid)
portal.sendDeliveryReceipt(mxid)
portal.log.Debugln("Handled message", message.Jid, "->", mxid)
}
func (portal *Portal) SyncParticipants(user *User, metadata *skypeExt.GroupInfo) {
changed := false
portal.log.Debugln("SyncParticipants start")
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
portal.log.Debugfln("SyncParticipants err: %+v", err)
levels = portal.GetBasePowerLevels()
changed = true
}
for _, participant := range metadata.Participants {
portal.log.Debugln("SyncParticipants: participant.JID= ", participant.JID)
// When synchronizing Skype room members, first look up whether there is a corresponding record in the user table.
// If there is, there are two possibilities:
// 1. This member is the puppet of the skype account A that you are currently importing,
// and has a corresponding matrix account
// 2. This member is a puppet of other people's skype account B.
// the other people have registered a matrix account in the same matrix server
// and have also synchronized (bridged) skype account B. skype A and skype B are in the same skype room.
participantUser := portal.bridge.GetUserByJID(participant.JID)
if participantUser != nil {
portal.log.Debugfln("SyncParticipants participantUser.JID: %$, user.JID: %s", participantUser.JID, user.JID)
if participantUser.JID != user.JID {
continue
}
}
portal.userMXIDAction(user, portal.ensureMXIDInvited)
puppet := portal.bridge.GetPuppetByJID(participant.JID)
portal.log.Debugln("SyncParticipants: portal.MXID = ", portal.MXID)
err := puppet.IntentFor(portal).EnsureJoined(portal.MXID)
if err != nil {
portal.log.Warnfln("Failed to make puppet of %s join %s: %+v", participant.JID, portal.MXID, err)
}
expectedLevel := 0
if participant.IsSuperAdmin {
expectedLevel = 95
} else if participant.IsAdmin {
expectedLevel = 50
}
changed = levels.EnsureUserLevel(puppet.MXID, expectedLevel) || changed
if participantUser != nil {
changed = levels.EnsureUserLevel(participantUser.MXID, expectedLevel) || changed
}
}
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels1:", err)
}
}
}
func (portal *Portal) UpdateAvatar(user *User, avatar *skypeExt.ProfilePicInfo) bool {
if avatar == nil || strings.Count(avatar.URL, "")-1 < 1 {
//var err error
//avatar, err = user.Conn.GetProfilePicThumb(portal.Key.JID)
//if err != nil {
// portal.log.Errorln(err)
// return false
//}
return false
}
avatar.Authorization = "skype_token " + user.Conn.LoginInfo.SkypeToken
if avatar.Status != 0 {
return false
}
if portal.Avatar == avatar.Tag {
return false
}
data, err := avatar.DownloadBytes()
if err != nil {
portal.log.Warnln("Failed to download avatar:", err)
return false
}
mimeType := http.DetectContentType(data)
resp, err := portal.MainIntent().UploadBytes(data, mimeType)
if err != nil {
portal.log.Warnln("Failed to upload avatar:", err)
return false
}
portal.AvatarURL = resp.ContentURI
if len(portal.MXID) > 0 {
_, err = portal.MainIntent().SetRoomAvatar(portal.MXID, resp.ContentURI)
if err != nil {
portal.log.Warnln("Failed to set room topic:", err)
return false
}
}
portal.Avatar = avatar.Tag
return true
}
func (portal *Portal) UpdateName(name string, setBy types.SkypeID) bool {
if portal.Name != name {
intent := portal.MainIntent()
if len(setBy) > 0 {
intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
}
_, err := intent.SetRoomName(portal.MXID, name)
if err == nil {
portal.Name = name
return true
}
portal.log.Warnln("Failed to set room name:", err)
}
return false
}
func (portal *Portal) UpdateTopic(topic string, setBy types.SkypeID) bool {
if portal.Topic != topic {
intent := portal.MainIntent()
if len(setBy) > 0 {
intent = portal.bridge.GetPuppetByJID(setBy).IntentFor(portal)
}
_, err := intent.SetRoomTopic(portal.MXID, topic)
if err == nil {
portal.Topic = topic
return true
}
portal.log.Warnln("Failed to set room topic:", err)
}
return false
}
func (portal *Portal) UpdateMetadata(user *User) bool {
if portal.IsPrivateChat() {
return false
} else if portal.IsStatusBroadcastRoom() {
update := false
update = portal.UpdateName("skype Status Broadcast", "") || update
update = portal.UpdateTopic("skype status updates from your contacts", "") || update
return update
}
metadata, err := user.Conn.GetGroupMetaData(portal.Key.JID)
if err != nil {
portal.log.Errorln(err)
fmt.Println()
fmt.Println("UpdateMetadata0: ", err)
fmt.Println()
return false
}
portalName := ""
noRoomTopic := false
names := strings.Split(metadata.Name, ", ")
for _, name := range names {
key := "8:" + name + skypeExt.NewUserSuffix
if key == user.JID {
noRoomTopic = true
}
}
if noRoomTopic {
for index, participant := range metadata.Participants {
fmt.Println()
fmt.Printf("metadata.Participants1: %+v", participant)
fmt.Println()
if participant.JID == user.JID {
continue
}
if contact, ok := user.Conn.Store.Contacts[participant.JID]; ok {
if len(portalName) == 0 {
portalName = contact.DisplayName
} else {
if index > 5 {
portalName = portalName + ", ..."
break
} else {
portalName = portalName + ", " + contact.DisplayName
}
}
}
}
} else {
portalName = metadata.Name
}
// portal.Topic = ""
//if metadata.Status != 0 {
// 401: access denied
// 404: group does (no longer) exist
// 500: ??? happens with status@broadcast
// TODO: update the room, e.g. change priority level
// to send messages to moderator
// return false
//}
portal.SyncParticipants(user, metadata)
update := false
update = portal.UpdateName(portalName, metadata.NameSetBy) || update
// update = portal.UpdateTopic(metadata.Topic, metadata.TopicSetBy) || update
return update
}
func (portal *Portal) userMXIDAction(user *User, fn func(mxid id.UserID)) {
if user == nil {
return
}
if user == portal.bridge.Relaybot {
for _, mxid := range portal.bridge.Config.Bridge.Relaybot.InviteUsers {
fn(mxid)
}
} else {
fn(user.MXID)
}
}
func (portal *Portal) ensureMXIDInvited(mxid id.UserID) {
portal.log.Debugfln("ensureMXIDInvited portal.MXID %s: %s", portal.MXID, mxid);
err := portal.MainIntent().EnsureInvited(portal.MXID, mxid)
if err != nil {
portal.log.Warnfln("Failed to ensure %s is invited to %s: %v", mxid, portal.MXID, err)
}
}
func (portal *Portal) ensureUserInvited(user *User) {
portal.userMXIDAction(user, portal.ensureMXIDInvited)
customPuppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if customPuppet != nil && customPuppet.CustomIntent() != nil {
_ = customPuppet.CustomIntent().EnsureJoined(portal.MXID)
}
}
func (portal *Portal) SyncSkype(user *User, chat skype.Conversation) {
portal.log.Infoln("Syncing portal for", user.MXID)
if user.IsRelaybot {
yes := true
portal.hasRelaybot = &yes
}
newPortal := false
if len(portal.MXID) == 0 {
if !portal.IsPrivateChat() {
portal.Name = chat.ThreadProperties.Topic
}
//todo
portal.log.Debugln("SyncSkype portal.MXID", portal.MXID)
err := portal.CreateMatrixRoom(user)
if err != nil {
portal.log.Errorln("Failed to create portal room:", err)
return
}
newPortal = true
} else {
portal.log.Debugln("SyncSkype ensureUserInvited", portal.MXID)
portal.ensureUserInvited(user)
//rep, err := portal.MainIntent().SetPowerLevel(portal.MXID, user.MXID, 95)
//if err != nil {
// portal.log.Warnfln("SyncSkype: SetPowerLevel err: ", err, rep)
//}
//if portal.IsPrivateChat() {
// preUserIds,_ := portal.GetMatrixUsers()
// for _,userId := range preUserIds {
// if user.MXID != userId {
// err := portal.tryKickUser(userId, portal.MainIntent())
// if err != nil {
// portal.log.Errorln("Failed to try kick user:", err)
// }
// }
// }
//}
}
if portal.IsPrivateChat() {
return
}
portal.log.Debugln("SyncSkype portal")
update := false
if !newPortal {
update = portal.UpdateMetadata(user) || update
}
// if !portal.IsStatusBroadcastRoom() {
//fmt.Println("SyncSkype portal.UpdateAvatar", portal.MXID)
// update = portal.UpdateAvatar(user, nil) || update
// }
if update {
portal.log.Debugln("SyncSkype portal.Update", portal.MXID)
portal.Update()
}
}
//func (portal *Portal) Sync(user *User, contact whatsapp.Contact) {
// portal.log.Infoln("Syncing portal for", user.MXID)
//
// if user.IsRelaybot {
// yes := true
// portal.hasRelaybot = &yes
// }
//
// if len(portal.MXID) == 0 {
// if !portal.IsPrivateChat() {
// portal.Name = contact.Name
// }
// err := portal.CreateMatrixRoom(user)
// if err != nil {
// portal.log.Errorln("Failed to create portal room:", err)
// return
// }
// } else {
// portal.ensureUserInvited(user)
// }
//
// if portal.IsPrivateChat() {
// return
// }
//
// update := false
// update = portal.UpdateMetadata(user) || update
// if !portal.IsStatusBroadcastRoom() {
// update = portal.UpdateAvatar(user, nil) || update
// }
// if update {
// portal.Update()
// }
//}
func (portal *Portal) GetBasePowerLevels() *event.PowerLevelsEventContent {
anyone := 0
nope := 95
invite := 50
if portal.bridge.Config.Bridge.AllowUserInvite {
invite = 0
}
return &event.PowerLevelsEventContent{
UsersDefault: anyone,
EventsDefault: anyone,
RedactPtr: &anyone,
StateDefaultPtr: &nope,
BanPtr: &nope,
InvitePtr: &invite,
Users: map[id.UserID]int{
portal.MainIntent().UserID: 100,
},
Events: map[string]int{
event.StateRoomName.Type: anyone,
event.StateRoomAvatar.Type: anyone,
event.StateTopic.Type: anyone,
},
}
}
func (portal *Portal) ChangeAdminStatus(jids []string, setAdmin bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
newLevel := 0
if setAdmin {
newLevel = 50
}
changed := false
for _, jid := range jids {
puppet := portal.bridge.GetPuppetByJID(jid)
changed = levels.EnsureUserLevel(puppet.MXID, newLevel) || changed
user := portal.bridge.GetUserByJID(jid)
if user != nil {
changed = levels.EnsureUserLevel(user.MXID, newLevel) || changed
}
}
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels2:", err)
}
}
}
//func (portal *Portal) membershipRemove(jids []string, action skypeExt.ChatActionType) {
// for _, jid := range jids {
// jidArr := strings.Split(jid, "@c.")
// jid = jidArr[0]
// member := portal.bridge.GetPuppetByJID(jid)
// if member == nil {
// portal.log.Errorln("%s is not exist", jid)
// continue
// }
// _, err := portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
// UserID: member.MXID,
// })
// if err != nil {
// portal.log.Errorln("Error %s member from skype: %v", action, err)
// }
// }
//}
func (portal *Portal) membershipRemove(content string) {
xmlFormat := skype.XmlDeleteMember{}
err := xml.Unmarshal([]byte(content), &xmlFormat)
for _, target := range xmlFormat.Targets {
member := portal.bridge.GetPuppetByJID(target)
memberMXID := id.UserID(patch.Parse(string(member.MXID)))
if portal.bridge.AS.StateStore.IsInRoom(portal.MXID, memberMXID) {
_, err = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
UserID: member.MXID,
})
if err != nil {
portal.log.Errorln("Error kick member from matrix after kick from skype: %v", err)
}
}
}
}
func (portal *Portal) membershipAdd(content string) {
xmlFormat := skype.XmlAddMember{}
err := xml.Unmarshal([]byte(content), &xmlFormat)
for _, target := range xmlFormat.Targets {
puppet := portal.bridge.GetPuppetByJID(target)
fmt.Println("membershipAdd puppet jid", target)
err = puppet.IntentFor(portal).EnsureJoined(portal.MXID)
if err != nil {
portal.log.Errorln("Error %v joined member from skype:", err)
}
}
}
func (portal *Portal) membershipCreate(user *User, cmd skypeExt.ChatUpdate) {
//contact := skype.Contact{
// Jid: cmd.Data.SenderJID,
// Notify: "",
// Name: cmd.Data.Create.Name,
// Short: "",
//}
//portal.Sync(user, contact)
//contact.Jid = cmd.JID
//user.Conn.Store.Contacts[cmd.JID] = contact
}
func (portal *Portal) RestrictMessageSending(restrict bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
if restrict {
levels.EventsDefault = 50
} else {
levels.EventsDefault = 0
}
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels3:", err)
}
}
func (portal *Portal) RestrictMetadataChanges(restrict bool) {
levels, err := portal.MainIntent().PowerLevels(portal.MXID)
if err != nil {
levels = portal.GetBasePowerLevels()
}
newLevel := 0
if restrict {
newLevel = 50
}
changed := false
changed = levels.EnsureEventLevel(event.StateRoomName, newLevel) || changed
changed = levels.EnsureEventLevel(event.StateRoomAvatar, newLevel) || changed
changed = levels.EnsureEventLevel(event.StateTopic, newLevel) || changed
if changed {
_, err = portal.MainIntent().SetPowerLevels(portal.MXID, levels)
if err != nil {
portal.log.Errorln("Failed to change power levels4:", err)
}
}
}
func (portal *Portal) BackfillHistory(user *User, lastMessageTime uint64) error {
if !portal.bridge.Config.Bridge.RecoverHistory {
return nil
}
endBackfill := portal.beginBackfill()
defer endBackfill()
lastMessage := portal.bridge.DB.Message.GetLastInChat(portal.Key)
if lastMessage == nil {
return nil
}
if lastMessage.Timestamp >= lastMessageTime {
portal.log.Debugln("Not backfilling: no new messages")
return nil
}
lastMessageID := lastMessage.JID
//lastMessageFromMe := lastMessage.Sender == user.JID
portal.log.Infoln("Backfilling history since", lastMessageID, "for", user.MXID)
for len(lastMessageID) > 0 {
portal.log.Debugln("Backfilling history: 50 messages after", lastMessageID)
//resp, err := user.Conn.LoadMessagesAfter(portal.Key.JID, lastMessageID, lastMessageFromMe, 50)
//if err != nil {
// return err
//}
//messages, ok := resp.Content.([]interface{})
//if !ok || len(messages) == 0 {
// break
//}
//portal.handleHistory(user, messages)
//
//lastMessageProto, ok := messages[len(messages)-1].(*waProto.WebMessageInfo)
//if ok {
// lastMessageID = lastMessageProto.GetKey().GetId()
// lastMessageFromMe = lastMessageProto.GetKey().GetFromMe()
//}
}
portal.log.Infoln("Backfilling finished")
return nil
}
func (portal *Portal) beginBackfill() func() {
portal.backfillLock.Lock()
portal.backfilling = true
var privateChatPuppetInvited bool
var privateChatPuppet *Puppet
if portal.IsPrivateChat() && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling {
receiverId := portal.Key.Receiver
if strings.Index(receiverId, skypeExt.NewUserSuffix) > 0 {
receiverId = strings.ReplaceAll(receiverId, skypeExt.NewUserSuffix, "")
}
privateChatPuppet = portal.bridge.GetPuppetByJID(receiverId)
portal.privateChatBackfillInvitePuppet = func() {
if privateChatPuppetInvited {
return
}
privateChatPuppetInvited = true
_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: privateChatPuppet.MXID})
_ = privateChatPuppet.DefaultIntent().EnsureJoined(portal.MXID)
}
}
return func() {
portal.backfilling = false
portal.privateChatBackfillInvitePuppet = nil
portal.backfillLock.Unlock()
if privateChatPuppet != nil && privateChatPuppetInvited {
_, homeserver, _ := privateChatPuppet.MXID.Parse()
if len(portal.bridge.Config.Bridge.LoginSharedSecretMap[homeserver]) > 0 {
_, _ = privateChatPuppet.DefaultIntent().LeaveRoom(portal.MXID)
}
}
}
}
func (portal *Portal) disableNotifications(user *User) {
if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
return
}
puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if puppet == nil || puppet.customIntent == nil {
return
}
portal.log.Debugfln("Disabling notifications for %s for backfilling", user.MXID)
ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
err := puppet.customIntent.PutPushRule("global", pushrules.OverrideRule, ruleID, &mautrix.ReqPutPushRule{
Actions: []pushrules.PushActionType{pushrules.ActionDontNotify},
Conditions: []pushrules.PushCondition{{
Kind: pushrules.KindEventMatch,
Key: "room_id",
Pattern: string(portal.MXID),
}},
})
if err != nil {
portal.log.Warnfln("Failed to disable notifications for %s while backfilling: %v", user.MXID, err)
}
}
func (portal *Portal) enableNotifications(user *User) {
if !portal.bridge.Config.Bridge.HistoryDisableNotifs {
return
}
puppet := portal.bridge.GetPuppetByCustomMXID(user.MXID)
if puppet == nil || puppet.customIntent == nil {
return
}
portal.log.Debugfln("Re-enabling notifications for %s after backfilling", user.MXID)
ruleID := fmt.Sprintf("net.maunium.silence_while_backfilling.%s", portal.MXID)
err := puppet.customIntent.DeletePushRule("global", pushrules.OverrideRule, ruleID)
if err != nil {
portal.log.Warnfln("Failed to re-enable notifications for %s after backfilling: %v", user.MXID, err)
}
}
func (portal *Portal) FillInitialHistory(user *User) error {
if portal.bridge.Config.Bridge.InitialHistoryFill == 0 {
return nil
}
endBackfill := portal.beginBackfill()
defer endBackfill()