forked from mautrix/signal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.go
1130 lines (1056 loc) · 33.4 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
// mautrix-signal - A Matrix-signal puppeting bridge.
// Copyright (C) 2023 Scott Weber
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/skip2/go-qrcode"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/bridge/commands"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-signal/pkg/libsignalgo"
"go.mau.fi/mautrix-signal/pkg/signalmeow"
"go.mau.fi/mautrix-signal/pkg/signalmeow/types"
)
var (
HelpSectionConnectionManagement = commands.HelpSection{Name: "Connection management", Order: 11}
HelpSectionCreatingPortals = commands.HelpSection{Name: "Creating portals", Order: 15}
HelpSectionPortalManagement = commands.HelpSection{Name: "Portal management", Order: 20}
HelpSectionInvites = commands.HelpSection{Name: "Group invites", Order: 25}
HelpSectionMiscellaneous = commands.HelpSection{Name: "Miscellaneous", Order: 30}
)
type WrappedCommandEvent struct {
*commands.Event
Bridge *SignalBridge
User *User
Portal *Portal
}
func (br *SignalBridge) RegisterCommands() {
proc := br.CommandProcessor.(*commands.Processor)
proc.AddHandlers(
cmdPing,
cmdLogin,
cmdSetDeviceName,
cmdPM,
cmdResolvePhone,
cmdSyncSpace,
cmdDeleteSession,
cmdSetRelay,
cmdUnsetRelay,
cmdDeletePortal,
cmdDeleteAllPortals,
cmdCleanupLostPortals,
cmdInviteLink,
cmdResetInviteLink,
cmdCreate,
cmdInvite,
cmdListInvited,
cmdRevokeInvite,
)
}
func wrapCommand(handler func(*WrappedCommandEvent)) func(*commands.Event) {
return func(ce *commands.Event) {
user := ce.User.(*User)
var portal *Portal
if ce.Portal != nil {
portal = ce.Portal.(*Portal)
}
br := ce.Bridge.Child.(*SignalBridge)
handler(&WrappedCommandEvent{ce, br, user, portal})
}
}
var cmdSetRelay = &commands.FullHandler{
Func: wrapCommand(fnSetRelay),
Name: "set-relay",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Relay messages in this room through your Signal account.",
},
RequiresPortal: true,
RequiresLogin: true,
}
func fnSetRelay(ce *WrappedCommandEvent) {
if !ce.Bridge.Config.Bridge.Relay.Enabled {
ce.Reply("Relay mode is not enabled on this instance of the bridge")
} else if ce.Bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
ce.Reply("Only bridge admins are allowed to enable relay mode on this instance of the bridge")
} else {
ce.Portal.RelayUserID = ce.User.MXID
ce.Portal.Update(ce.Ctx)
ce.Reply("Messages from non-logged-in users in this room will now be bridged through your Signal account")
}
}
var cmdUnsetRelay = &commands.FullHandler{
Func: wrapCommand(fnUnsetRelay),
Name: "unset-relay",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Stop relaying messages in this room.",
},
RequiresPortal: true,
}
func fnUnsetRelay(ce *WrappedCommandEvent) {
if !ce.Bridge.Config.Bridge.Relay.Enabled {
ce.Reply("Relay mode is not enabled on this instance of the bridge")
} else if ce.Bridge.Config.Bridge.Relay.AdminOnly && !ce.User.Admin {
ce.Reply("Only bridge admins are allowed to enable relay mode on this instance of the bridge")
} else {
ce.Portal.RelayUserID = ""
ce.Portal.Update(ce.Ctx)
ce.Reply("Messages from non-logged-in users will no longer be bridged in this room")
}
}
var cmdDeleteSession = &commands.FullHandler{
Func: wrapCommand(fnDeleteSession),
Name: "delete-session",
Help: commands.HelpMeta{
Section: HelpSectionConnectionManagement,
Description: "Disconnect from Signal, clearing sessions but keeping other data. Reconnect with `login`",
},
}
func fnDeleteSession(ce *WrappedCommandEvent) {
if !ce.User.IsLoggedIn() {
ce.Reply("You're not logged in")
return
}
ce.User.Client.ClearKeysAndDisconnect(ce.Ctx)
ce.Reply("Disconnected from Signal")
}
var cmdPing = &commands.FullHandler{
Func: wrapCommand(fnPing),
Name: "ping",
Help: commands.HelpMeta{
Section: commands.HelpSectionAuth,
Description: "Check your connection to Signal",
},
}
func fnPing(ce *WrappedCommandEvent) {
if ce.User.SignalID == uuid.Nil {
ce.Reply("You're not logged in")
} else if !ce.User.IsLoggedIn() {
ce.Reply("You were logged in at some point, but are not anymore")
} else if !ce.User.Client.IsConnected() {
ce.Reply("You're logged into Signal, but not connected to the server")
} else {
ce.Reply("You're logged into Signal and probably connected to the server")
}
}
var cmdSetDeviceName = &commands.FullHandler{
Func: wrapCommand(fnSetDeviceName),
Name: "set-device-name",
Help: commands.HelpMeta{
Section: HelpSectionConnectionManagement,
Description: "Set the name of this device in Signal",
Args: "<name>",
},
RequiresLogin: true,
}
func fnSetDeviceName(ce *WrappedCommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `set-device-name <name>`")
return
}
name := strings.Join(ce.Args, " ")
err := ce.User.Client.UpdateDeviceName(ce.Ctx, name)
if err != nil {
ce.Reply("Error setting device name: %v", err)
return
}
ce.Reply("Device name updated")
}
var cmdPM = &commands.FullHandler{
Func: wrapCommand(fnPM),
Name: "pm",
Help: commands.HelpMeta{
Section: HelpSectionCreatingPortals,
Description: "Open a private chat with the given phone number.",
Args: "<_international phone number_>",
},
RequiresLogin: true,
}
var numberCleaner = strings.NewReplacer("-", "", " ", "", "(", "", ")", "", "+", "")
func fnPM(ce *WrappedCommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `pm <international phone number>`")
return
}
number, err := strconv.ParseUint(numberCleaner.Replace(strings.Join(ce.Args, "")), 10, 64)
if err != nil {
ce.Reply("Failed to parse number")
return
}
user := ce.User
var aci, pni uuid.UUID
e164 := fmt.Sprintf("+%d", number)
var recipient *types.Recipient
if recipient, err = user.Client.ContactByE164(ce.Ctx, e164); err != nil {
ce.Reply("Error looking up number in local contact list: %v", err)
return
} else if recipient != nil && (recipient.ACI != uuid.Nil || recipient.PNI != uuid.Nil) {
// TODO maybe lookup PNI if there's only ACI and E164 stored?
aci = recipient.ACI
pni = recipient.PNI
} else if resp, err := user.Client.LookupPhone(ce.Ctx, number); err != nil {
ce.ZLog.Err(err).Uint64("e164", number).Msg("Failed to lookup number on server")
ce.Reply("Error looking up number on server: %v", err)
return
} else {
aci = resp[number].ACI
pni = resp[number].PNI
if aci == uuid.Nil && pni == uuid.Nil {
ce.Reply("+%d doesn't seem to be on Signal", number)
return
}
recipient, err = user.Client.Store.RecipientStore.UpdateRecipientE164(ce.Ctx, aci, pni, e164)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to save recipient entry after looking up phone")
}
aci, pni = recipient.ACI, recipient.PNI
}
ce.ZLog.Debug().
Uint64("e164", number).
Stringer("aci", aci).
Stringer("pni", pni).
Msg("Found DM target user")
var targetServiceID libsignalgo.ServiceID
if aci != uuid.Nil {
targetServiceID = libsignalgo.NewACIServiceID(aci)
} else {
targetServiceID = libsignalgo.NewPNIServiceID(pni)
}
portal := user.GetPortalByChatID(targetServiceID.String())
if portal == nil {
ce.Reply("Couldn't get portal with %s/+%d", targetServiceID, number)
return
} else if portal.MXID != "" {
ok := portal.ensureUserInvited(ce.Ctx, ce.User)
if ok {
ce.Reply("You already have a portal with +%d at [%s](%s)", number, portal.MXID, portal.MXID.URI(portal.bridge.Config.Homeserver.Domain).MatrixToURL())
return
}
ce.ZLog.Warn().Stringer("existing_room_id", portal.MXID).Msg("Ensuring user is invited to existing room failed, creating new room")
portal.Cleanup(ce.Ctx, false)
portal.MXID = ""
}
if err = portal.CreateMatrixRoom(ce.Ctx, user, 0); err != nil {
ce.ZLog.Err(err).Msg("Failed to create portal room")
ce.Reply("Error creating Matrix room for portal to +%d", number)
} else {
ce.Reply("Created portal room [%s](%s) with +%d and invited you to it.", portal.MXID, portal.MXID.URI(portal.bridge.Config.Homeserver.Domain).MatrixToURL(), number)
}
}
var cmdInvite = &commands.FullHandler{
Func: wrapCommand(fnInvite),
Name: "invite",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Invite a user by phone number.",
Args: "<_international phone number_>",
},
RequiresLogin: true,
RequiresPortal: true,
}
func fnInvite(ce *WrappedCommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `invite <international phone number>`")
return
}
number, err := strconv.ParseUint(numberCleaner.Replace(strings.Join(ce.Args, "")), 10, 64)
if err != nil {
ce.Reply("Failed to parse number")
return
}
user := ce.User
var aci, pni uuid.UUID
e164 := fmt.Sprintf("+%d", number)
var recipient *types.Recipient
if recipient, err = user.Client.ContactByE164(ce.Ctx, e164); err != nil {
ce.Reply("Error looking up number in local contact list: %v", err)
return
} else if recipient != nil && (recipient.ACI != uuid.Nil || recipient.PNI != uuid.Nil) {
// TODO maybe lookup PNI if there's only ACI and E164 stored?
aci = recipient.ACI
pni = recipient.PNI
} else if resp, err := user.Client.LookupPhone(ce.Ctx, number); err != nil {
ce.ZLog.Err(err).Uint64("e164", number).Msg("Failed to lookup number on server")
ce.Reply("Error looking up number on server: %v", err)
return
} else {
aci = resp[number].ACI
pni = resp[number].PNI
if aci == uuid.Nil && pni == uuid.Nil {
ce.Reply("+%d doesn't seem to be on Signal", number)
return
}
recipient, err = user.Client.Store.RecipientStore.UpdateRecipientE164(ce.Ctx, aci, pni, e164)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to save recipient entry after looking up phone")
}
aci, pni = recipient.ACI, recipient.PNI
}
ce.ZLog.Debug().
Uint64("e164", number).
Stringer("aci", aci).
Stringer("pni", pni).
Msg("Found Invite target user")
var groupChange signalmeow.GroupChange
if aci != uuid.Nil {
groupChange.AddMembers = []*signalmeow.AddMember{
{
GroupMember: signalmeow.GroupMember{
ACI: aci,
Role: signalmeow.GroupMember_DEFAULT,
},
},
}
} else {
groupChange.AddPendingMembers = []*signalmeow.PendingMember{
{
ServiceID: libsignalgo.NewPNIServiceID(pni),
AddedByUserID: ce.User.SignalID,
Role: signalmeow.GroupMember_DEFAULT,
},
}
}
revision, err := ce.User.Client.UpdateGroup(ce.Ctx, &groupChange, ce.Portal.GroupID())
if err != nil {
ce.Reply("Failed to update group: %w", err)
return
}
ce.Portal.Revision = revision
if aci != uuid.Nil {
group, err := ce.User.Client.RetrieveGroupByID(ce.Ctx, ce.Portal.GroupID(), revision)
if err != nil {
ce.Reply("Failed to fetch group after invite: %w", err)
}
ce.Portal.SyncParticipants(ce.Ctx, user, group)
ce.Portal.Update(ce.Ctx)
return
}
ce.Portal.Update(ce.Ctx)
ce.Reply("Invited " + e164)
}
var cmdListInvited = &commands.FullHandler{
Func: wrapCommand(fnListInvited),
Name: "list-invited",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "list pending invites",
Args: "<_international phone number_>",
},
RequiresLogin: true,
RequiresPortal: true,
}
func fnListInvited(ce *WrappedCommandEvent) {
group, err := ce.User.Client.RetrieveGroupByID(ce.Ctx, ce.Portal.GroupID(), ce.Portal.Revision)
if err != nil {
ce.Reply("Failed to fetch group info: %w", err)
return
}
var memberList []string
for _, pendingMember := range group.PendingMembers {
recipientString, err := pendingMemberToString(ce.Ctx, ce.User, pendingMember)
if err != nil {
ce.Reply("Failed to fetch recipient for %s: %w", pendingMember.ServiceID, err)
continue
}
memberList = append(memberList, recipientString)
}
if len(memberList) == 0 {
ce.Reply("No pending Invites")
} else {
ce.Reply(strings.Join(memberList, "\n"))
}
}
func pendingMemberToString(ctx context.Context, user *User, pendingMember *signalmeow.PendingMember) (string, error) {
var pni, aci uuid.UUID
if pendingMember.ServiceID.Type == libsignalgo.ServiceIDTypeACI {
aci = pendingMember.ServiceID.UUID
} else {
pni = pendingMember.ServiceID.UUID
}
recipient, err := user.Client.Store.RecipientStore.LoadAndUpdateRecipient(ctx, aci, pni, nil)
if err != nil {
return "", err
}
if recipient.E164 != "" {
return recipient.E164, nil
} else {
return "Unidentified User", nil
}
}
var cmdRevokeInvite = &commands.FullHandler{
Func: wrapCommand(fnRevokeInvite),
Name: "revoke-invite",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Revoke an invite by phone number.",
Args: "<_international phone number_>",
},
RequiresLogin: true,
RequiresPortal: true,
}
func fnRevokeInvite(ce *WrappedCommandEvent) {
if len(ce.Args) == 0 {
ce.Reply("**Usage:** `RevokeInvite <international phone number>`")
return
}
e164 := "+" + numberCleaner.Replace(strings.Join(ce.Args, ""))
user := ce.User
var serviceID libsignalgo.ServiceID
group, err := ce.User.Client.RetrieveGroupByID(ce.Ctx, ce.Portal.GroupID(), ce.Portal.Revision)
if err != nil {
ce.Reply("Failed to fetch group info: %w", err)
return
}
var pni, aci uuid.UUID
for _, pendingMember := range group.PendingMembers {
if pendingMember.ServiceID.Type == libsignalgo.ServiceIDTypeACI {
aci = pendingMember.ServiceID.UUID
} else {
pni = pendingMember.ServiceID.UUID
}
recipient, err := user.Client.Store.RecipientStore.LoadAndUpdateRecipient(ce.Ctx, aci, pni, nil)
if err != nil {
continue
}
if recipient.E164 == e164 {
serviceID = pendingMember.ServiceID
break
}
}
if serviceID.UUID == uuid.Nil {
ce.Reply("User not in Group")
return
}
var groupChange signalmeow.GroupChange
groupChange.DeletePendingMembers = []*libsignalgo.ServiceID{&serviceID}
revision, err := ce.User.Client.UpdateGroup(ce.Ctx, &groupChange, ce.Portal.GroupID())
if err != nil {
ce.Reply("Failed to update group: %w", err)
return
}
if aci != uuid.Nil {
target := ce.Bridge.GetPuppetBySignalID(aci)
if target != nil {
ce.Bot.SendCustomMembershipEvent(ce.Ctx, ce.Portal.MXID, target.IntentFor(ce.Portal).UserID, event.MembershipLeave, "removed by "+user.MXID.String())
}
}
ce.Portal.Revision = revision
ce.Portal.Update(ce.Ctx)
ce.Reply("Revoked the invitation for " + e164)
}
var cmdResolvePhone = &commands.FullHandler{
Func: wrapCommand(fnResolvePhone),
Name: "resolve-phone",
Help: commands.HelpMeta{
Section: HelpSectionCreatingPortals,
Description: "Look up phone numbers on the Signal servers.",
Args: "<numbers...>",
},
RequiresLogin: true,
}
func fnResolvePhone(ce *WrappedCommandEvent) {
numbers := make([]uint64, len(ce.Args))
for i, arg := range ce.Args {
var err error
numbers[i], err = strconv.ParseUint(numberCleaner.Replace(arg), 10, 64)
if err != nil {
ce.Reply("Failed to parse number %s: %v", arg, err)
return
}
}
resp, err := ce.User.Client.LookupPhone(ce.Ctx, numbers...)
if err != nil {
ce.Reply("Failed to look up: %v", err)
} else {
var out strings.Builder
for _, phone := range numbers {
result, found := resp[phone]
if found {
_, _ = fmt.Fprintf(&out, "+%d: %s / %s\n", phone, result.ACI, result.PNI)
} else {
_, _ = fmt.Fprintf(&out, "+%d: not found\n", phone)
}
}
ce.Reply(strings.TrimSpace(out.String()))
}
}
var cmdSyncSpace = &commands.FullHandler{
Func: wrapCommand(fnSyncSpace),
Name: "sync-space",
Help: commands.HelpMeta{
Section: HelpSectionMiscellaneous,
Description: "Synchronize your personal filtering space",
},
RequiresLogin: true,
}
func fnSyncSpace(ce *WrappedCommandEvent) {
if !ce.Bridge.Config.Bridge.PersonalFilteringSpaces {
ce.Reply("Personal filtering spaces are not enabled on this instance of the bridge")
return
}
ctx := ce.Ctx
dmKeys, err := ce.Bridge.DB.Portal.FindPrivateChatsNotInSpace(ctx, ce.User.SignalID)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to get private chat keys")
ce.Reply("Failed to get private chat IDs from database")
return
}
count := 0
allPortals := ce.Bridge.GetAllPortalsWithMXID()
for _, portal := range allPortals {
if portal.IsPrivateChat() {
continue
}
if ce.Bridge.StateStore.IsInRoom(ctx, portal.MXID, ce.User.MXID) && portal.addToPersonalSpace(ctx, ce.User) {
count++
}
}
for _, key := range dmKeys {
portal := ce.Bridge.GetPortalByChatID(key)
portal.addToPersonalSpace(ctx, ce.User)
count++
}
plural := "s"
if count == 1 {
plural = ""
}
ce.Reply("Added %d room%s to space", count, plural)
}
var cmdLogin = &commands.FullHandler{
Func: wrapCommand(fnLogin),
Name: "login",
Help: commands.HelpMeta{
Section: commands.HelpSectionAuth,
Description: "Link the bridge to your Signal account as a web client.",
},
}
func fnLogin(ce *WrappedCommandEvent) {
if ce.User.IsLoggedIn() {
if ce.User.Client.IsConnected() {
ce.Reply("You're already logged in")
} else {
ce.Reply("You're already logged in, but not connected 🤔")
}
return
}
var qrEventID, msgEventID id.EventID
var signalID uuid.UUID
var signalPhone string
// First get the provisioning URL
provChan, err := ce.User.Login()
if err != nil {
ce.ZLog.Err(err).Msg("Failure logging in")
ce.Reply("Failure logging in: %v", err)
return
}
resp := <-provChan
if resp.Err != nil || resp.State == signalmeow.StateProvisioningError {
ce.Reply("Error getting provisioning URL: %v", resp.Err)
return
}
if resp.State == signalmeow.StateProvisioningURLReceived {
qrEventID, msgEventID = ce.User.sendQR(ce, resp.ProvisioningURL, qrEventID, msgEventID)
} else {
ce.Reply("Unexpected state: %v", resp.State)
return
}
// Next, get the results of finishing registration
resp = <-provChan
_, _ = ce.Bot.RedactEvent(ce.Ctx, ce.RoomID, qrEventID)
_, _ = ce.Bot.RedactEvent(ce.Ctx, ce.RoomID, msgEventID)
if resp.Err != nil || resp.State == signalmeow.StateProvisioningError {
if resp.Err != nil && strings.HasSuffix(resp.Err.Error(), " EOF") {
ce.Reply("Logging in timed out, please try again.")
} else {
ce.Reply("Error finishing registration: %v", resp.Err)
}
return
}
if resp.State == signalmeow.StateProvisioningDataReceived {
signalID = resp.ProvisioningData.ACI
signalPhone = resp.ProvisioningData.Number
} else {
ce.Reply("Unexpected state: %v", resp.State)
return
}
// Finally, get the results of generating and registering prekeys
resp = <-provChan
if resp.Err != nil || resp.State == signalmeow.StateProvisioningError {
ce.Reply("Error with prekeys: %v", resp.Err)
return
} else if resp.State != signalmeow.StateProvisioningPreKeysRegistered {
ce.Reply("Unexpected state: %v", resp.State)
return
}
if signalID == uuid.Nil {
ce.Reply("Problem logging in - No SignalID received")
return
}
ce.User.saveSignalID(ce.Ctx, signalID, signalPhone)
// Connect to Signal
ce.User.Connect()
ce.Reply("Successfully logged in as %s (UUID: %s)", ce.User.SignalUsername, ce.User.SignalID)
}
func (user *User) sendQR(ce *WrappedCommandEvent, code string, prevQR, prevMsg id.EventID) (qr, msg id.EventID) {
content, ok := user.uploadQR(ce, code)
if !ok {
return prevQR, prevMsg
}
if len(prevQR) != 0 {
content.SetEdit(prevQR)
}
resp, err := ce.Bot.SendMessageEvent(ce.Ctx, ce.RoomID, event.EventMessage, &content)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to send QR code to user")
} else if len(prevQR) == 0 {
prevQR = resp.EventID
}
content = event.MessageEventContent{
MsgType: event.MsgNotice,
Body: fmt.Sprintf("Raw linking URI: %s", code),
Format: event.FormatHTML,
FormattedBody: fmt.Sprintf("Raw linking URI: <code>%s</code>", code),
}
if len(prevMsg) != 0 {
content.SetEdit(prevMsg)
}
resp, err = ce.Bot.SendMessageEvent(ce.Ctx, ce.RoomID, event.EventMessage, &content)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to send raw code to user")
} else if len(prevMsg) == 0 {
prevMsg = resp.EventID
}
return prevQR, prevMsg
}
func (user *User) uploadQR(ce *WrappedCommandEvent, code string) (event.MessageEventContent, bool) {
const size = 512
qrCode, err := qrcode.Encode(code, qrcode.Low, size)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to encode QR code")
ce.Reply("Failed to encode QR code: %v", err)
return event.MessageEventContent{}, false
}
bot := user.bridge.AS.BotClient()
resp, err := bot.UploadBytes(ce.Ctx, qrCode, "image/png")
if err != nil {
ce.ZLog.Err(err).Msg("Failed to upload QR code")
ce.Reply("Failed to upload QR code: %v", err)
return event.MessageEventContent{}, false
}
return event.MessageEventContent{
MsgType: event.MsgImage,
Info: &event.FileInfo{
MimeType: "image/png",
Width: size,
Height: size,
Size: len(qrCode),
},
Body: "qr.png",
URL: resp.ContentURI.CUString(),
}, true
}
func canDeletePortal(ctx context.Context, portal *Portal, userID id.UserID) bool {
if len(portal.MXID) == 0 {
return false
}
members, err := portal.MainIntent().JoinedMembers(ctx, portal.MXID)
if err != nil {
portal.log.Err(err).
Stringer("user_id", userID).
Msg("Failed to get joined members to check if user can delete portal")
return false
}
for otherUser := range members.Joined {
_, isPuppet := portal.bridge.ParsePuppetMXID(otherUser)
if isPuppet || otherUser == portal.bridge.Bot.UserID || otherUser == userID {
continue
}
user := portal.bridge.GetUserByMXID(otherUser)
if user != nil && user.IsLoggedIn() {
return false
}
}
return true
}
var cmdDeletePortal = &commands.FullHandler{
Func: wrapCommand(fnDeletePortal),
Name: "delete-portal",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Delete the current portal. If the portal is used by other people, this is limited to bridge admins.",
},
RequiresPortal: true,
}
func fnDeletePortal(ce *WrappedCommandEvent) {
if !ce.User.Admin && !canDeletePortal(ce.Ctx, ce.Portal, ce.User.MXID) {
ce.Reply("Only bridge admins can delete portals with other Matrix users")
return
}
ce.Portal.log.Info().Stringer("user_id", ce.User.MXID).Msg("User requested deletion of portal")
ce.Portal.Delete()
ce.Portal.Cleanup(ce.Ctx, false)
}
var cmdDeleteAllPortals = &commands.FullHandler{
Func: wrapCommand(fnDeleteAllPortals),
Name: "delete-all-portals",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Delete all portals.",
},
}
func fnDeleteAllPortals(ce *WrappedCommandEvent) {
portals := ce.Bridge.GetAllPortalsWithMXID()
var portalsToDelete []*Portal
if ce.User.Admin {
portalsToDelete = portals
} else {
portalsToDelete = portals[:0]
for _, portal := range portals {
if canDeletePortal(ce.Ctx, portal, ce.User.MXID) {
portalsToDelete = append(portalsToDelete, portal)
}
}
}
if len(portalsToDelete) == 0 {
ce.Reply("Didn't find any portals to delete")
return
}
leave := func(portal *Portal) {
if len(portal.MXID) > 0 {
_, _ = portal.MainIntent().KickUser(ce.Ctx, portal.MXID, &mautrix.ReqKickUser{
Reason: "Deleting portal",
UserID: ce.User.MXID,
})
}
}
customPuppet := ce.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(ce.Ctx, portal.MXID)
_, _ = intent.ForgetRoom(ce.Ctx, portal.MXID)
}
}
}
ce.Reply("Found %d portals, deleting...", len(portalsToDelete))
for _, portal := range portalsToDelete {
portal.Delete()
leave(portal)
}
ce.Reply("Finished deleting portal info. Now cleaning up rooms in background.")
backgroundCtx := context.TODO()
go func() {
for _, portal := range portalsToDelete {
portal.Cleanup(backgroundCtx, false)
}
ce.Reply("Finished background cleanup of deleted portal rooms.")
}()
}
var cmdCleanupLostPortals = &commands.FullHandler{
Func: wrapCommand(fnCleanupLostPortals),
Name: "cleanup-lost-portals",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Clean up portals that were discarded due to the receiver not being logged into the bridge",
},
RequiresAdmin: true,
}
func fnCleanupLostPortals(ce *WrappedCommandEvent) {
portals, err := ce.Bridge.DB.LostPortal.GetAll(ce.Ctx)
if err != nil {
ce.Reply("Failed to get portals: %v", err)
return
} else if len(portals) == 0 {
ce.Reply("No lost portals found")
return
}
ce.Reply("Found %d lost portals, deleting...", len(portals))
for _, portal := range portals {
dmUUID, err := uuid.Parse(portal.ChatID)
intent := ce.Bot
if err == nil {
intent = ce.Bridge.GetPuppetBySignalID(dmUUID).DefaultIntent()
}
ce.Bridge.CleanupRoom(ce.Ctx, ce.ZLog, intent, portal.MXID, false)
err = portal.Delete(ce.Ctx)
if err != nil {
ce.ZLog.Err(err).Msg("Failed to delete lost portal from database after cleanup")
}
}
ce.Reply("Finished cleaning up portals")
}
var cmdInviteLink = &commands.FullHandler{
Func: wrapCommand(fnInviteLink),
Name: "invite-link",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Get the invite link for the corresponding Signal Group",
},
RequiresLogin: true,
}
func fnInviteLink(ce *WrappedCommandEvent) {
if ce.Portal == nil {
ce.Reply("This is not a portal room")
return
}
if ce.Portal.IsPrivateChat() {
ce.Reply("Invite Links are not available for private chats")
return
}
inviteLinkPassword, err := ce.Portal.GetInviteLink(ce.Ctx, ce.User)
if err != nil {
ce.Reply("Error getting invite link %w", err)
return
}
ce.Reply(inviteLinkPassword)
}
var cmdResetInviteLink = &commands.FullHandler{
Func: wrapCommand(fnResetInviteLink),
Name: "reset-invite-link",
Help: commands.HelpMeta{
Section: HelpSectionPortalManagement,
Description: "Generate a new invite link password",
},
RequiresLogin: true,
}
func fnResetInviteLink(ce *WrappedCommandEvent) {
if ce.Portal == nil {
ce.Reply("This is not a portal room")
return
}
if ce.Portal.IsPrivateChat() {
ce.Reply("Invite Links are not available for private chats")
return
}
err := ce.Portal.ResetInviteLink(ce.Ctx, ce.User)
if err != nil {
ce.Reply("Error setting new invite link %w", err)
}
inviteLink, err := ce.Portal.GetInviteLink(ce.Ctx, ce.User)
if err != nil {
ce.Reply("Error getting new invite link %w", err)
return
}
ce.Reply(inviteLink)
}
var cmdCreate = &commands.FullHandler{
Func: wrapCommand(fnCreate),
Name: "create",
Help: commands.HelpMeta{
Section: HelpSectionCreatingPortals,
Description: "Create a Signal group chat for the current Matrix room.",
},
RequiresLogin: true,
}
func fnCreate(ce *WrappedCommandEvent) {
if ce.Portal != nil {
ce.Reply("This is already a portal room")
return
}
roomState, err := ce.Bot.State(ce.Ctx, ce.RoomID)
if err != nil {
ce.Reply("Failed to get room state: %w", err)
return
}
members := roomState[event.StateMember]
powerLevelsRaw, ok := roomState[event.StatePowerLevels][""]
if !ok {
ce.Reply("Failed to get room power levels")
return
}
powerLevelsRaw.Content.ParseRaw(event.StatePowerLevels)
powerLevels := powerLevelsRaw.Content.AsPowerLevels()
joinRulesRaw, ok := roomState[event.StateJoinRules][""]
if !ok {
ce.Reply("Failed to get join rules")
return
}
joinRulesRaw.Content.ParseRaw(event.StateJoinRules)
joinRule := joinRulesRaw.Content.AsJoinRules().JoinRule
roomNameEventRaw, ok := roomState[event.StateRoomName][""]
if !ok {
ce.Reply("Failed to get room name")
return
}
roomNameEventRaw.Content.ParseRaw(event.StateRoomName)
roomName := roomNameEventRaw.Content.AsRoomName().Name
if len(roomName) == 0 {
ce.Reply("Please set a name for the room first")
return
}
roomTopic := ""
roomTopicEvent, ok := roomState[event.StateTopic][""]
if ok {
roomTopicEvent.Content.ParseRaw(event.StateTopic)
roomTopic = roomTopicEvent.Content.AsTopic().Topic
}
roomAvatarEvent, ok := roomState[event.StateRoomAvatar][""]
var avatarHash string
var avatarURL id.ContentURI
var avatarBytes []byte
avatarSet := false
if ok {
roomAvatarEvent.Content.ParseRaw(event.StateRoomAvatar)
avatarURL = roomAvatarEvent.Content.AsRoomAvatar().URL
if !avatarURL.IsEmpty() {
avatarBytes, err = ce.Bot.DownloadBytes(ce.Ctx, avatarURL)
if err != nil {
ce.ZLog.Err(err).Stringer("Failed to download updated avatar %s", avatarURL)
return
}
hash := sha256.Sum256(avatarBytes)
avatarHash = hex.EncodeToString(hash[:])