forked from kelaresg/go-skype-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.go
1184 lines (1072 loc) · 34.5 KB
/
commands.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 (
"errors"
"fmt"
"math"
skype "github.com/kelaresg/go-skypeapi"
"github.com/kelaresg/matrix-skype/database"
skypeExt "github.com/kelaresg/matrix-skype/skype-ext"
"maunium.net/go/mautrix/patch"
"sort"
"strconv"
"strings"
"maunium.net/go/maulogger/v2"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
)
type CommandHandler struct {
bridge *Bridge
log maulogger.Logger
}
// NewCommandHandler creates a CommandHandler
func NewCommandHandler(bridge *Bridge) *CommandHandler {
return &CommandHandler{
bridge: bridge,
log: bridge.Log.Sub("Command handler"),
}
}
// CommandEvent stores all data which might be used to handle commands
type CommandEvent struct {
Bot *appservice.IntentAPI
Bridge *Bridge
Portal *Portal
Handler *CommandHandler
RoomID id.RoomID
User *User
Command string
Args []string
}
// Reply sends a reply to command as notice
func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
content.MsgType = event.MsgNotice
intent := ce.Bot
if ce.Portal != nil && ce.Portal.IsPrivateChat() {
intent = ce.Portal.MainIntent()
}
_, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
if err != nil {
ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
}
}
// Handle handles messages to the bridge
func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
args := strings.Fields(message)
ce := &CommandEvent{
Bot: handler.bridge.Bot,
Bridge: handler.bridge,
Handler: handler,
RoomID: roomID,
User: user,
Command: strings.ToLower(args[0]),
Args: args[1:],
}
if ce.Command == "login" {
message = ""
}
handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
handler.CommandRelaybot(ce)
} else {
handler.CommandMux(ce)
}
}
func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
switch ce.Command {
case "relaybot":
handler.CommandRelaybot(ce)
case "login":
handler.CommandLogin(ce)
//case "logout-matrix":
// handler.CommandLogoutMatrix(ce)
case "help":
handler.CommandHelp(ce)
//case "version":
// handler.CommandVersion(ce)
case "ping":
handler.CommandPing(ce)
case "logout":
handler.CommandLogout(ce)
case "save-password":
handler.CommandSavePassword(ce)
case "remove-password":
handler.CommandRemovePassword(ce)
case "login-matrix", "sync", "list", "open", "pm", "invite", "kick", "leave", "join", "create", "share":
if !ce.User.HasSession() {
ce.Reply("You're not logged in. Use the `login` command to log into Skype.")
return
}
switch ce.Command {
//case "login-matrix":
// handler.CommandLoginMatrix(ce)
case "sync":
handler.CommandSync(ce)
case "list":
handler.CommandList(ce)
case "open":
handler.CommandOpen(ce)
case "pm":
handler.CommandPM(ce)
case "invite":
handler.CommandInvite(ce)
case "kick":
handler.CommandKick(ce)
case "leave":
handler.CommandLeave(ce)
case "join":
handler.CommandJoin(ce)
case "share":
handler.CommandShare(ce)
case "create":
handler.CommandCreate(ce)
}
default:
handler.CommandSpecialMux(ce)
}
}
func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
if handler.bridge.Relaybot == nil {
ce.Reply("The relaybot is disabled")
} else if !ce.User.Admin {
ce.Reply("Only admins can manage the relaybot")
} else {
if ce.Command == "relaybot" {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `relaybot <command>`")
return
}
ce.Command = strings.ToLower(ce.Args[0])
ce.Args = ce.Args[1:]
}
ce.User = handler.bridge.Relaybot
handler.CommandMux(ce)
}
}
func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
}
const cmdVersionHelp = `version - View the bridge version`
func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
version := fmt.Sprintf("v%s.unknown", Version)
if Tag == Version {
version = fmt.Sprintf("[v%s](%s/releases/v%s) (%s)", Version, URL, Tag, BuildTime)
} else if len(Commit) > 8 {
version = fmt.Sprintf("v%s.[%s](%s/commit/%s) (%s)", Version, Commit[:8], URL, Commit, BuildTime)
}
ce.Reply(fmt.Sprintf("[%s](%s) %s", Name, URL, version))
}
const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
if portal == nil {
ce.Reply("Not a portal room")
return
}
var level int
var userID id.UserID
var err error
if len(ce.Args) == 1 {
level, err = strconv.Atoi(ce.Args[0])
if err != nil {
ce.Reply("Invalid power level \"%s\"", ce.Args[0])
return
}
userID = ce.User.MXID
} else if len(ce.Args) == 2 {
userID = id.UserID(ce.Args[0])
_, _, err := userID.Parse()
if err != nil {
ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
return
}
level, err = strconv.Atoi(ce.Args[1])
if err != nil {
ce.Reply("Invalid power level \"%s\"", ce.Args[1])
return
}
} else {
ce.Reply("**Usage:** `set-pl [user] <level>`")
return
}
intent := portal.MainIntent()
_, err = intent.SetPowerLevel(ce.RoomID, userID, level)
if err != nil {
ce.Reply("Failed to set power levels: %v", err)
}
}
const cmdLoginHelp = `login - login <_username_> <_password_>`
// CommandLogin handles login command
func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `login username password`")
return
}
if ce.User.Conn != nil && ce.User.Conn.LoggedIn == true {
ce.Reply("You're already logged into Skype.")
return
}
leavePortals(ce)
if !ce.User.Connect(true) {
ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
return
}
err := ce.User.Login(ce, ce.Args[0], ce.Args[1])
if err == nil {
syncAll(ce.User, true)
}
}
const cmdLogoutHelp = `logout - Logout from Skype`
func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
if ce.User.Conn == nil || ce.User.Conn.LoggedIn == false {
ce.Reply("You're not logged into Skype.")
return
}
//_ = ce.User.Conn.GetConversations("", ce.User.bridge.Config.Bridge.InitialChatSync)
ce.User.Conn.LoggedIn = false
username := ""
password := ""
if ce.User.Conn.LoginInfo != nil {
username = ce.User.Conn.LoginInfo.Username
password = ce.User.Conn.LoginInfo.Password
}
ce.User.Conn.LoginInfo = &skype.Session{
SkypeToken: "",
SkypeExpires: "",
RegistrationToken: "",
RegistrationTokenStr: "",
RegistrationExpires: "",
LocationHost: "",
EndpointId: "",
Username: username,
Password: password,
}
ce.User.Conn.Store = &skype.Store{
Contacts: make(map[string]skype.Contact),
Chats: make(map[string]skype.Conversation),
}
puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
if puppet.CustomMXID != "" {
err := puppet.SwitchCustomMXID("", "")
if err != nil {
ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
}
}
ce.Reply("Logged out successfully.")
ce.User.Conn.LoginInfo = nil
if ce.User.Conn.Refresh != nil {
ce.User.Conn.Refresh <- -1
} else {
leavePortals(ce)
}
ret := ce.User.bridge.DB.User.GetCredentialsByMXID(ce.User.MXID, &password, &username)
if ret && password != "" {
ce.Reply("WARNING, your password is stored in database. Use command `remove-password` to remove it.")
}
}
const cmdSavePasswordHelp = `save-password - save user password into database`
// CommandSavePassword handles save-password command
func (handler *CommandHandler) CommandSavePassword(ce *CommandEvent) {
var ret bool
if len(ce.Args) > 0 {
ce.Reply("**Usage:** `save-password`")
return
}
if ce.User.Conn == nil || ce.User.Conn.LoggedIn == false {
ce.Reply("You're not logged into Skype.")
return
}
ret = ce.User.bridge.DB.User.SetCredentialsByMXID(ce.User.Conn.LoginInfo.Password, ce.User.Conn.LoginInfo.Username, ce.User.MXID)
if ret == true {
ce.Reply("Your password was successfully saved into database.")
} else {
ce.Reply("An error occurred while saving your password into database. Try it again.")
}
}
const cmdRemovePasswordHelp = `remove-password - remove user password from database`
// CommandRemovePassword handles remove-password command
func (handler *CommandHandler) CommandRemovePassword(ce *CommandEvent) {
var ret bool
if len(ce.Args) > 0 {
ce.Reply("**Usage:** `remove-password`")
return
}
ret = ce.User.bridge.DB.User.SetCredentialsByMXID("", "", ce.User.MXID)
if ret == true {
ce.Reply("Your password was successfully removed from database.")
} else {
ce.Reply("An error occurred while removing your password from database. Try it again.")
}
}
func leavePortals(ce *CommandEvent) {
portals := ce.User.GetPortals()
//newPortals := ce.User.GetPortalsNew()
//allPortals := newPortals[0:]
//for _, portal := range portals {
// var newPortalsHas bool
// for _, newPortal := range newPortals {
// if portal.Key == newPortal.Key {
// newPortalsHas = true
// }
// }
// if !newPortalsHas {
// allPortals = append(allPortals, portal)
// }
//}
leave := func(portal *Portal) {
if len(portal.MXID) > 0 {
_, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
Reason: "Logout",
UserID: ce.User.MXID,
})
}
}
for _, portal := range portals {
leave(portal)
}
}
const cmdPingHelp = `ping - Check your connection to Skype.`
func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
if ce.User.Session == nil || ce.User.Session.SkypeToken == "" {
if ce.User.IsLoginInProgress() {
ce.Reply("You're not logged into Skype, but there's a login in progress.")
} else {
ce.Reply("You're not logged into Skype.")
}
} else if ce.User.Conn.LoggedIn == false {
ce.Reply("You're not logged into Skype.")
} else {
username := ce.User.Conn.UserProfile.FirstName
if len(ce.User.Conn.UserProfile.LastName) > 0 {
username = username + ce.User.Conn.UserProfile.LastName
}
if username == "" {
username = ce.User.Conn.UserProfile.Username
}
orgId := ""
if patch.ThirdPartyIdEncrypt {
orgId = patch.Enc(strings.TrimSuffix(ce.User.JID, skypeExt.NewUserSuffix))
} else {
orgId = strings.TrimSuffix(ce.User.JID, skypeExt.NewUserSuffix)
}
ce.Reply("You're logged in as @" + username + ", orgid is " + orgId)
}
var password string;
var username string;
ret := ce.User.bridge.DB.User.GetCredentialsByMXID(ce.User.MXID, &password, &username)
if ret && password != "" {
ce.Reply("WARNING, your password is stored in database. Use command `remove-password` to remove it.")
}
}
const cmdHelpHelp = `help - Prints this help`
// CommandHelp handles help command
func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
cmdPrefix := ""
if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
}
ce.Reply("* " + strings.Join([]string{
cmdPrefix + cmdHelpHelp,
cmdPrefix + cmdLoginHelp,
cmdPrefix + cmdLogoutHelp,
cmdPrefix + cmdSavePasswordHelp,
cmdPrefix + cmdRemovePasswordHelp,
cmdPrefix + cmdPingHelp,
//cmdPrefix + cmdLoginMatrixHelp,
//cmdPrefix + cmdLogoutMatrixHelp,
cmdPrefix + cmdSyncHelp,
cmdPrefix + cmdListHelp,
cmdPrefix + cmdOpenHelp,
cmdPrefix + cmdPMHelp,
cmdPrefix + cmdCreateHelp,
cmdPrefix + cmdInviteHelp,
cmdPrefix + cmdKickHelp,
cmdPrefix + cmdLeaveHelp,
cmdPrefix + cmdJoinHelp,
cmdPrefix + cmdShareHelp,
}, "\n* "))
}
const cmdSyncHelp = `sync - Synchronize contacts and optionally create portals for group chats.`
func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
user := ce.User
create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
ce.Reply("Updating contact and chat list...")
handler.log.Debugln("Importing contacts of", user.MXID)
ce.Reply("Syncing contacts...")
err := user.Conn.Conn.ContactList(ce.User.Conn.UserProfile.Username)
if err != nil {
user.log.Errorln("Error get contacts:", err)
ce.Reply("Failed to contacts chat list (see logs for details)")
}
ce.Reply("Syncing conversations...")
err = ce.User.Conn.GetConversations("", user.bridge.Config.Bridge.InitialChatSync)
if err != nil {
user.log.Errorln("Error get conversations:", err)
ce.Reply("Failed to conversations list (see logs for details)")
}
handler.log.Debugln("Importing chats of", user.MXID)
syncAll(user, create)
ce.Reply("Sync complete.")
}
func syncAll(user *User, create bool) {
//ce.Reply("Syncing contacts...")
user.syncPuppets(nil, false)
//ce.Reply("Syncing chats...")
user.syncPortals(nil, create)
//sync information from non-contacts in the conversation,
syncNonContactInfo(user)
}
func syncNonContactInfo(user *User) {
nonContacts := map[string]skype.Contact{}
for personId, contact := range user.Conn.Store.Contacts {
if contact.PersonId == "" {
nonContacts[personId] = contact
}
}
user.syncPuppets(nonContacts, false)
user.syncPuppets(nil, true)
}
const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
if portal == nil {
ce.Reply("You must be in a portal room to use that command")
return
}
if !ce.User.Admin {
users := portal.GetUserIDs()
if len(users) > 1 || (len(users) == 1 && users[0] != ce.User.MXID) {
ce.Reply("Only bridge admins can delete portals with other Matrix users")
return
}
}
portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
portal.Delete()
portal.Cleanup(false)
}
const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all your portals that aren't used by any other user.'`
func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
portals := ce.User.GetPortals()
portalsToDelete := make([]*Portal, 0, len(portals))
for _, portal := range portals {
users := portal.GetUserIDs()
if len(users) == 1 && users[0] == ce.User.MXID {
portalsToDelete = append(portalsToDelete, portal)
}
}
leave := func(portal *Portal) {
if len(portal.MXID) > 0 {
_, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
Reason: "Deleting portal",
UserID: ce.User.MXID,
})
}
}
customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
if customPuppet != nil && customPuppet.CustomIntent() != nil {
intent := customPuppet.CustomIntent()
leave = func(portal *Portal) {
if len(portal.MXID) > 0 {
_, _ = intent.LeaveRoom(portal.MXID)
_, _ = intent.ForgetRoom(portal.MXID)
}
}
}
ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
for _, portal := range portalsToDelete {
portal.Delete()
leave(portal)
}
ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
"You may already continue using the bridge. Use `sync` to recreate portals.")
go func() {
for _, portal := range portalsToDelete {
portal.Cleanup(false)
}
ce.Reply("Finished background cleanup of deleted portal rooms.")
}()
}
const cmdListHelp = `list <_contacts|groups_> [page] [items per page] - Get a list of all contacts and groups.`
func formatLists(isContacts bool, contacts map[string]skype.Contact, conversations map[string]skype.Conversation) (result []string) {
if isContacts {
for _, contact := range contacts {
result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.DisplayName, contact.DisplayNameSource, strings.Replace(contact.PersonId, skypeExt.NewUserSuffix, "", 1)))
}
sort.Sort(sort.StringSlice(result))
} else {
for _, conversation := range conversations {
if strings.HasPrefix(fmt.Sprint(conversation.Id), "19:") {
result = append(result, fmt.Sprintf("* %s - `%s`", conversation.ThreadProperties.Topic, conversation.Id))
}
}
sort.Sort(sort.StringSlice(result))
}
return
}
func (handler *CommandHandler) CommandList(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
return
}
mode := strings.ToLower(ce.Args[0])
if mode[0] != 'g' && mode[0] != 'c' {
ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
return
}
var err error
page := 1
max := 100
isContact := mode[0] == 'c'
typeName := "Groups"
if isContact {
typeName = "Contacts"
err = ce.User.Conn.ContactList(ce.User.Conn.UserProfile.Username)
if err != nil {
ce.Reply("Get Contacts error")
return
}
} else {
err = ce.User.Conn.GetConversations("", handler.bridge.Config.Bridge.InitialChatSync)
if err != nil {
ce.Reply("Get conversations error")
return
}
}
result := formatLists(isContact, ce.User.Conn.Store.Contacts, ce.User.Conn.Store.Chats)
if len(result) == 0 {
ce.Reply("No %s found", strings.ToLower(typeName))
return
}
pages := int(math.Ceil(float64(len(result)) / float64(max)))
if (page-1)*max >= len(result) {
if pages == 1 {
ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
} else {
ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
}
return
}
lastIndex := page * max
if lastIndex > len(result) {
lastIndex = len(result)
}
result = result[(page-1)*max : lastIndex]
ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
}
const cmdOpenHelp = `open <_group ID_> - Open a group chat portal.`
func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `open <group ID>`")
return
}
user := ce.User
jid := ce.Args[0]
if strings.HasSuffix(jid, skypeExt.NewUserSuffix) {
ce.Reply("That looks like a user ID. Did you mean `pm %s`?", jid[:len(jid)-len(skypeExt.NewUserSuffix)])
return
}
ce.User.Conn.GetConversations("", handler.bridge.Config.Bridge.InitialChatSync)
fmt.Println("user.Conn.Store.Chats: ", user.Conn.Store.Chats)
chat, ok := user.Conn.Store.Chats[jid]
if !ok {
ce.Reply("Group ID not found in contacts. Try syncing contacts with `sync` first.")
return
}
handler.log.Debugln("Importing", jid, "for", user)
portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
fmt.Println("CommandOpen portal.MXID", portal.MXID)
if len(portal.MXID) > 0 {
portal.SyncSkype(user, chat)
ce.Reply("Portal room synced.")
} else {
portal.SyncSkype(user, chat)
ce.Reply("Portal room created.")
}
_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
//resp, err := ce.User.Conn.GetConsumptionHorizons(jid)
//if err != nil {
// return
//}
//// var existIds []string
//for _, con := range resp.ConsumptionHorizons {
// // existIds = append(existIds, strings.Replace(userId, skypeExt.NewUserSuffix, "", 1))
// has := false
// uId := ""
// for userId, _ := range ce.User.Conn.Store.Contacts {
// if con.Id == strings.Replace(userId, skypeExt.NewUserSuffix, "", 1) {
// has = true
// }
// uId = con.Id
// }
// if user.JID == con.Id + skypeExt.NewUserSuffix {
// continue
// }
// if !has && uId != "" {
// fmt.Println(fmt.Sprintf("https://avatar.skype.com/v1/avatars/%s/public?returnDefaultImage=false", uId))
// fmt.Println()
// newId := strings.Replace(con.Id, "8:", "", 1)
// avatar := &skypeExt.ProfilePicInfo{
// URL: fmt.Sprintf("https://avatar.skype.com/v1/avatars/%s/public?returnDefaultImage=false", newId),
// Tag: fmt.Sprintf("https://avatar.skype.com/v1/avatars/%s/public?returnDefaultImage=false", newId),
// Status: 0,
// }
// puppet := user.bridge.GetPuppetByJID(con.Id + skypeExt.NewUserSuffix)
// if puppet.Avatar != avatar.URL {
// puppet.UpdateAvatar(nil, avatar)
// _, err = ce.User.Conn.NameSearch(newId)
// if err != nil {
// ce.Reply("Failed to synchronize non-contact %s info", newId)
// }
// }
// }
//}
syncNonContactInfo(ce.User)
}
//func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
// if len(ce.Args) == 0 {
// ce.Reply("**Usage:** `open <group JID>`")
// return
// }
//
// user := ce.User
// jid := ce.Args[0]
//
// if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
// ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)])
// return
// }
//
// contact, ok := user.Conn.Store.Contacts[jid]
// if !ok {
// ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
// return
// }
// handler.log.Debugln("Importing", jid, "for", user)
// portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
// if len(portal.MXID) > 0 {
// portal.Sync(user, contact)
// ce.Reply("Portal room synced.")
// } else {
// portal.Sync(user, contact)
// ce.Reply("Portal room created.")
// }
// _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
//}
const cmdPMHelp = `pm <_user ID_> - Open a private chat with the given user id.`
func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `pm <user id>`")
return
}
jid := ce.Args[0] + skypeExt.NewUserSuffix
handler.log.Debugln("Importing", jid, "for", ce.User)
contact, ok := ce.User.Conn.Store.Contacts[jid]
if !ok {
//if !force {
ce.Reply("User id not found in contacts. Try syncing contacts with `sync` first. ")
return
//}
//contact = skype.Contact{PersonId: jid}
}
puppet := ce.User.bridge.GetPuppetByJID(contact.PersonId)
puppet.Sync(ce.User, contact)
portal := ce.User.bridge.GetPortalByJID(database.NewPortalKey(ce.Args[0], ce.User.JID))
fmt.Println("CommandPM user.JID", ce.User.JID)
if len(portal.MXID) > 0 {
_, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: ce.User.MXID})
if err != nil {
fmt.Println(err)
} else {
ce.Reply("Existing portal room found, invited you to it.")
}
return
}
err := portal.CreateMatrixRoom(ce.User)
if err != nil {
ce.Reply("Failed to create portal room: %v", err)
return
}
ce.Reply("Created portal room and invited you to it.")
}
//func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
// if len(ce.Args) == 0 {
// ce.Reply("**Usage:** `pm [--force] <international phone number>`")
// return
// }
//
// force := ce.Args[0] == "--force"
// if force {
// ce.Args = ce.Args[1:]
// }
//
// user := ce.User
//
// number := strings.Join(ce.Args, "")
// if number[0] == '+' {
// number = number[1:]
// }
// for _, char := range number {
// if char < '0' || char > '9' {
// ce.Reply("Invalid phone number.")
// return
// }
// }
// jid := number + whatsappExt.NewUserSuffix
//
// handler.log.Debugln("Importing", jid, "for", user)
//
// contact, ok := user.Conn.Store.Contacts[jid]
// if !ok {
// if !force {
// ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
// "To create a portal anyway, use `pm --force <number>`.")
// return
// }
// contact = whatsapp.Contact{Jid: jid}
// }
// puppet := user.bridge.GetPuppetByJID(contact.Jid)
// puppet.Sync(user, contact)
// portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
// if len(portal.MXID) > 0 {
// _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
// if err != nil {
// fmt.Println(err)
// } else {
// ce.Reply("Existing portal room found, invited you to it.")
// }
// return
// }
// err := portal.CreateMatrixRoom(user)
// if err != nil {
// ce.Reply("Failed to create portal room: %v", err)
// return
// }
// ce.Reply("Created portal room and invited you to it.")
//}
const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `login-matrix <access token>`")
return
}
puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
if err != nil {
ce.Reply("Failed to switch puppet: %v", err)
return
}
ce.Reply("Successfully switched puppet")
}
const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
if len(puppet.CustomMXID) == 0 {
ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
return
}
err := puppet.SwitchCustomMXID("", "")
if err != nil {
ce.Reply("Failed to remove custom puppet: %v", err)
return
}
ce.Reply("Successfully removed custom puppet")
}
const cmdInviteHelp = `invite <_group ID_> <_contact id_>,... - Invite members to a group.`
func (handler *CommandHandler) CommandInvite(ce *CommandEvent) {
if len(ce.Args) < 2 {
ce.Reply("**Usage:** `invite <group JID> <contact id>,...`")
return
}
user := ce.User
conversationId := ce.Args[0]
userNumbers := strings.Split(ce.Args[1], ",")
if strings.HasSuffix(conversationId, skypeExt.NewUserSuffix) {
ce.Reply("**Usage:** `invite <group JID> <contact id>,...`")
return
}
_, ok := user.Conn.Store.Chats[conversationId]
if !ok {
//user.Conn
err := ce.User.Conn.GetConversations("", handler.bridge.Config.Bridge.InitialChatSync)
//time.Sleep(5 * time.Second)
if err != nil {
ce.Reply("get conversations failed. Try syncing contacts with `sync` first.")
} else {
_, ok = user.Conn.Store.Chats[conversationId]
if !ok {
ce.Reply("Group JID not found in chats. Try syncing groups with `sync` first.")
return
}
}
}
handler.log.Debugln("GetConversations", conversationId, "for", user)
handler.log.Debugln("Inviting", userNumbers, "to", conversationId)
err := user.Conn.HandleGroupInvite(conversationId, userNumbers)
if err != nil {
ce.Reply("Please confirm that you have permission to invite members.")
} else {
ce.Reply("Group invitation sent.\nIf the member fails to join the group, please check your permissions or command parameters")
}
}
const cmdKickHelp = `kick <_group ID_> <_contact Id>,... - Remove members from the group.`
func (handler *CommandHandler) CommandKick(ce *CommandEvent) {
if len(ce.Args) < 2 {
ce.Reply("**Usage:** `kick <group JID> <contact jid>,... reason`")
return
}
user := ce.User
converationId := ce.Args[0]
userNumbers := strings.Split(ce.Args[1], ",")
//reason := "omitempty"
//if len(ce.Args) > 2 {
// reason = ce.Args[0]
//}
if strings.HasSuffix(converationId, skypeExt.NewUserSuffix) {
ce.Reply("**Usage:** `kick <group ID> <contact id>,... reason`")
return
}
//fmt.Println("user:", user)
//fmt.Println("chats", user.Conn.Store.Chats)
_, ok := user.Conn.Store.Chats[converationId]
//fmt.Println("查找用户组是否存在:")
//fmt.Println(group)
if !ok {
ce.Reply("Group ID not found in contacts. Try syncing contacts with `sync` first.")
return
}
handler.log.Debugln("Importing", converationId, "for", user)
portal := user.bridge.GetPortalByJID(database.GroupPortalKey(converationId))
for i, number := range userNumbers {
userNumbers[i] = number // + skypeExt.NewUserSuffix
member := portal.bridge.GetPuppetByJID(number + skypeExt.NewUserSuffix)
if member == nil {
portal.log.Errorln("%s is not a puppet", number)
return
}
}
handler.log.Debugln("Kicking", userNumbers, "to", converationId)
err := user.Conn.HandleGroupKick(converationId, userNumbers)
if err != nil {
handler.log.Errorln("Kicking err", err)
ce.Reply("Please confirm that you have permission to kick members.")
} else {
ce.Reply("Remove operation completed.\nIf the member has not been removed, please check your permissions or command parameters")
}
}
const cmdLeaveHelp = `leave <_group ID_> - Leave a group.`
func (handler *CommandHandler) CommandLeave(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `leave <group JID>`")
return
}
user := ce.User
groupId := ce.Args[0]
if strings.HasSuffix(groupId, skypeExt.NewUserSuffix) {
ce.Reply("**Usage:** `leave <group JID>`")
return
}
//
handler.log.Debugln("Importing", groupId, "for", user)
portal := user.bridge.GetPortalByJID(database.GroupPortalKey(groupId))
if len(portal.MXID) > 0 {
cli := handler.bridge.Bot
fmt.Println("cli appurl:", cli.Prefix, cli.AppServiceUserID, cli.HomeserverURL.String())
//res, errLeave := cli.LeaveRoom(portal.MXID)
//cli.AppServiceUserID = ce.User.MXID
u := cli.BuildURL("rooms", portal.MXID, "leave")
fmt.Println(u)
resp := mautrix.RespLeaveRoom{}
res, err := cli.MakeRequest("POST", u, struct{}{}, &resp)
fmt.Println("leave res : ", res)
fmt.Println("leave res err: ", err)
//if errLeave != nil {
// portal.log.Errorln("Error leaving matrix room:", errLeave)
//}
}
err := user.Conn.HandleGroupLeave(groupId)
if err != nil {
fmt.Println(err)
ce.Reply("Leave operation failed.")
return
}
ce.Reply("Leave operation completed and successful.")
}
const cmdShareHelp = `share <_group ID_> - Generate a link to join the group.`
func (handler *CommandHandler) CommandShare(ce *CommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `share <group id>`")
return
}
user := ce.User
converationId := ce.Args[0]
fmt.Println("share converationId : ", converationId)
//check the group is exists
_, ok := user.Conn.Store.Chats[converationId]