Double puppet support
This commit is contained in:
@@ -43,8 +43,9 @@ type Bridge struct {
|
||||
portalsByID map[database.PortalKey]*Portal
|
||||
portalsLock sync.Mutex
|
||||
|
||||
puppets map[string]*Puppet
|
||||
puppetsLock sync.Mutex
|
||||
puppets map[string]*Puppet
|
||||
puppetsByCustomMXID map[id.UserID]*Puppet
|
||||
puppetsLock sync.Mutex
|
||||
|
||||
StateStore *database.SQLStateStore
|
||||
}
|
||||
@@ -97,7 +98,8 @@ func New(cfg *config.Config) (*Bridge, error) {
|
||||
portalsByMXID: make(map[id.RoomID]*Portal),
|
||||
portalsByID: make(map[database.PortalKey]*Portal),
|
||||
|
||||
puppets: make(map[string]*Puppet),
|
||||
puppets: make(map[string]*Puppet),
|
||||
puppetsByCustomMXID: make(map[id.UserID]*Puppet),
|
||||
|
||||
StateStore: stateStore,
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ func (h *commandHandler) handle(roomID id.RoomID, user *User, message string, re
|
||||
if err != nil {
|
||||
h.log.Warnf("Failed to parse command %q: %v", message, err)
|
||||
|
||||
cmd.globals.reply("failed to process the command")
|
||||
cmd.globals.reply(fmt.Sprintf("failed to process the command: %v", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,8 +52,15 @@ type commands struct {
|
||||
Logout logoutCmd `kong:"cmd,help='Log out of Discord.'"`
|
||||
Reconnect reconnectCmd `kong:"cmd,help='Reconnect to Discord'"`
|
||||
Version versionCmd `kong:"cmd,help='Displays the version of the bridge.'"`
|
||||
|
||||
LoginMatrix loginMatrixCmd `kong:"cmd,help='Replace the puppet for your Discord account with your real Matrix account.'"`
|
||||
LogoutMatrix logoutMatrixCmd `kong:"cmd,help='Switch the puppet for your Discord account back to the default one.'"`
|
||||
PingMatrix pingMatrixCmd `kong:"cmd,help='check if your double puppet is working properly'"`
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Help Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type helpCmd struct {
|
||||
Command []string `kong:"arg,optional,help='The command to get help on.'"`
|
||||
}
|
||||
@@ -78,6 +85,9 @@ func (c *helpCmd) Run(g *globals) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Version Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type versionCmd struct{}
|
||||
|
||||
func (c *versionCmd) Run(g *globals) error {
|
||||
@@ -86,6 +96,9 @@ func (c *versionCmd) Run(g *globals) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Login Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type loginCmd struct{}
|
||||
|
||||
func (l *loginCmd) Run(g *globals) error {
|
||||
@@ -108,7 +121,7 @@ func (l *loginCmd) Run(g *globals) error {
|
||||
|
||||
_, err := g.user.sendQRCode(g.bot, g.roomID, code)
|
||||
if err != nil {
|
||||
fmt.Fprintln(g.context.Stdout, "failed to generate the qrcode")
|
||||
fmt.Fprintln(g.context.Stdout, "Failed to generate the qrcode")
|
||||
|
||||
return
|
||||
}
|
||||
@@ -127,23 +140,30 @@ func (l *loginCmd) Run(g *globals) error {
|
||||
|
||||
user, err := client.Result()
|
||||
if err != nil {
|
||||
fmt.Println(g.context.Stdout, "failed to log in")
|
||||
fmt.Fprintln(g.context.Stdout, "Failed to log in")
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if err := g.user.Login(user.Token); err != nil {
|
||||
fmt.Println(g.context.Stdout, "failed to login", err)
|
||||
fmt.Fprintln(g.context.Stdout, "Failed to login", err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
g.user.Lock()
|
||||
g.user.ID = user.UserID
|
||||
g.user.Update()
|
||||
g.user.Unlock()
|
||||
|
||||
fmt.Fprintln(g.context.Stdout, "Successfully logged in")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Logout Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type logoutCmd struct{}
|
||||
|
||||
func (l *logoutCmd) Run(g *globals) error {
|
||||
@@ -165,6 +185,9 @@ func (l *logoutCmd) Run(g *globals) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Disconnect Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type disconnectCmd struct{}
|
||||
|
||||
func (d *disconnectCmd) Run(g *globals) error {
|
||||
@@ -185,6 +208,9 @@ func (d *disconnectCmd) Run(g *globals) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Reconnect Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type reconnectCmd struct{}
|
||||
|
||||
func (r *reconnectCmd) Run(g *globals) error {
|
||||
@@ -204,3 +230,59 @@ func (r *reconnectCmd) Run(g *globals) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// LoginMatrix Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type loginMatrixCmd struct {
|
||||
AccessToken string `kong:"arg,help='The shared secret to use the bridge'"`
|
||||
}
|
||||
|
||||
func (m *loginMatrixCmd) Run(g *globals) error {
|
||||
puppet := g.bridge.GetPuppetByID(g.user.ID)
|
||||
|
||||
err := puppet.SwitchCustomMXID(m.AccessToken, g.user.MXID)
|
||||
if err != nil {
|
||||
fmt.Fprintf(g.context.Stdout, "Failed to switch puppet: %v", err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Fprintf(g.context.Stdout, "Successfully switched puppet")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// LogoutMatrix Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type logoutMatrixCmd struct{}
|
||||
|
||||
func (m *logoutMatrixCmd) Run(g *globals) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// PingMatrix Command
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
type pingMatrixCmd struct{}
|
||||
|
||||
func (m *pingMatrixCmd) Run(g *globals) error {
|
||||
puppet := g.bridge.GetPuppetByCustomMXID(g.user.MXID)
|
||||
if puppet == nil || puppet.CustomIntent() == nil {
|
||||
fmt.Fprintf(g.context.Stdout, "You have not changed your Discord account's Matrix puppet.")
|
||||
|
||||
return fmt.Errorf("double puppet not configured")
|
||||
}
|
||||
|
||||
resp, err := puppet.CustomIntent().Whoami()
|
||||
if err != nil {
|
||||
fmt.Fprintf(g.context.Stdout, "Failed to validate Matrix login: %v", err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Fprintf(g.context.Stdout, "Confirmed valid access token for %s / %s", resp.UserID, resp.DeviceID)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
337
bridge/custompuppet.go
Normal file
337
bridge/custompuppet.go
Normal file
@@ -0,0 +1,337 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"maunium.net/go/mautrix"
|
||||
"maunium.net/go/mautrix/appservice"
|
||||
"maunium.net/go/mautrix/event"
|
||||
"maunium.net/go/mautrix/id"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoCustomMXID = errors.New("no custom mxid set")
|
||||
ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
|
||||
)
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// additional bridge api
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
func (b *Bridge) newDoublePuppetClient(mxid id.UserID, accessToken string) (*mautrix.Client, error) {
|
||||
_, homeserver, err := mxid.Parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
homeserverURL, found := b.Config.Bridge.DoublePuppetServerMap[homeserver]
|
||||
if !found {
|
||||
if homeserver == b.as.HomeserverDomain {
|
||||
homeserverURL = b.as.HomeserverURL
|
||||
} else if b.Config.Bridge.DoublePuppetAllowDiscovery {
|
||||
resp, err := mautrix.DiscoverClientAPI(homeserver)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to find homeserver URL for %s: %v", homeserver, err)
|
||||
}
|
||||
|
||||
homeserverURL = resp.Homeserver.BaseURL
|
||||
b.log.Debugfln("Discovered URL %s for %s to enable double puppeting for %s", homeserverURL, homeserver, mxid)
|
||||
} else {
|
||||
return nil, fmt.Errorf("double puppeting from %s is not allowed", homeserver)
|
||||
}
|
||||
}
|
||||
|
||||
client, err := mautrix.NewClient(homeserverURL, mxid, accessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client.Logger = b.as.Log.Sub(mxid.String())
|
||||
client.Client = b.as.HTTPClient
|
||||
client.DefaultHTTPRetries = b.as.DefaultHTTPRetries
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// mautrix.Syncer implementation
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
func (p *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
|
||||
everything := []event.Type{{Type: "*"}}
|
||||
return &mautrix.Filter{
|
||||
Presence: mautrix.FilterPart{
|
||||
Senders: []id.UserID{p.CustomMXID},
|
||||
Types: []event.Type{event.EphemeralEventPresence},
|
||||
},
|
||||
AccountData: mautrix.FilterPart{NotTypes: everything},
|
||||
Room: mautrix.RoomFilter{
|
||||
Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
|
||||
IncludeLeave: false,
|
||||
AccountData: mautrix.FilterPart{NotTypes: everything},
|
||||
State: mautrix.FilterPart{NotTypes: everything},
|
||||
Timeline: mautrix.FilterPart{NotTypes: everything},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
|
||||
p.log.Warnln("Sync error:", err)
|
||||
if errors.Is(err, mautrix.MUnknownToken) {
|
||||
if !p.tryRelogin(err, "syncing") {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
p.customIntent.AccessToken = p.AccessToken
|
||||
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return 10 * time.Second, nil
|
||||
}
|
||||
|
||||
func (p *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
|
||||
if !p.customUser.LoggedIn() {
|
||||
p.log.Debugln("Skipping sync processing: custom user not connected to discord")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// for roomID, events := range resp.Rooms.Join {
|
||||
// for _, evt := range events.Ephemeral.Events {
|
||||
// evt.RoomID = roomID
|
||||
// err := evt.Content.ParseRaw(evt.Type)
|
||||
// if err != nil {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// switch evt.Type {
|
||||
// case event.EphemeralEventReceipt:
|
||||
// if p.EnableReceipts {
|
||||
// go p.bridge.matrixHandler.HandleReceipt(evt)
|
||||
// }
|
||||
// case event.EphemeralEventTyping:
|
||||
// go p.bridge.matrixHandler.HandleTyping(evt)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// if p.EnablePresence {
|
||||
// for _, evt := range resp.Presence.Events {
|
||||
// if evt.Sender != p.CustomMXID {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// err := evt.Content.ParseRaw(evt.Type)
|
||||
// if err != nil {
|
||||
// continue
|
||||
// }
|
||||
|
||||
// go p.bridge.matrixHandler.HandlePresence(evt)
|
||||
// }
|
||||
// }
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// mautrix.Storer implementation
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
func (p *Puppet) SaveFilterID(_ id.UserID, _ string) {
|
||||
}
|
||||
|
||||
func (p *Puppet) SaveNextBatch(_ id.UserID, nbt string) {
|
||||
p.NextBatch = nbt
|
||||
p.Update()
|
||||
}
|
||||
|
||||
func (p *Puppet) SaveRoom(_ *mautrix.Room) {
|
||||
}
|
||||
|
||||
func (p *Puppet) LoadFilterID(_ id.UserID) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (p *Puppet) LoadNextBatch(_ id.UserID) string {
|
||||
return p.NextBatch
|
||||
}
|
||||
|
||||
func (p *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room {
|
||||
return nil
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// additional puppet api
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
func (p *Puppet) clearCustomMXID() {
|
||||
p.CustomMXID = ""
|
||||
p.AccessToken = ""
|
||||
p.customIntent = nil
|
||||
p.customUser = nil
|
||||
}
|
||||
|
||||
func (p *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
|
||||
if p.CustomMXID == "" {
|
||||
return nil, ErrNoCustomMXID
|
||||
}
|
||||
|
||||
client, err := p.bridge.newDoublePuppetClient(p.CustomMXID, p.AccessToken)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client.Syncer = p
|
||||
client.Store = p
|
||||
|
||||
ia := p.bridge.as.NewIntentAPI("custom")
|
||||
ia.Client = client
|
||||
ia.Localpart, _, _ = p.CustomMXID.Parse()
|
||||
ia.UserID = p.CustomMXID
|
||||
ia.IsCustomPuppet = true
|
||||
|
||||
return ia, nil
|
||||
}
|
||||
|
||||
func (p *Puppet) StartCustomMXID(reloginOnFail bool) error {
|
||||
if p.CustomMXID == "" {
|
||||
p.clearCustomMXID()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
intent, err := p.newCustomIntent()
|
||||
if err != nil {
|
||||
p.clearCustomMXID()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := intent.Whoami()
|
||||
if err != nil {
|
||||
if !reloginOnFail || (errors.Is(err, mautrix.MUnknownToken) && !p.tryRelogin(err, "initializing double puppeting")) {
|
||||
p.clearCustomMXID()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
intent.AccessToken = p.AccessToken
|
||||
} else if resp.UserID != p.CustomMXID {
|
||||
p.clearCustomMXID()
|
||||
|
||||
return ErrMismatchingMXID
|
||||
}
|
||||
|
||||
p.customIntent = intent
|
||||
p.customUser = p.bridge.GetUserByMXID(p.CustomMXID)
|
||||
p.startSyncing()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Puppet) tryRelogin(cause error, action string) bool {
|
||||
if !p.bridge.Config.CanAutoDoublePuppet(p.CustomMXID) {
|
||||
return false
|
||||
}
|
||||
|
||||
p.log.Debugfln("Trying to relogin after '%v' while %s", cause, action)
|
||||
|
||||
accessToken, err := p.loginWithSharedSecret(p.CustomMXID)
|
||||
if err != nil {
|
||||
p.log.Errorfln("Failed to relogin after '%v' while %s: %v", cause, action, err)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
p.log.Infofln("Successfully relogined after '%v' while %s", cause, action)
|
||||
p.AccessToken = accessToken
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *Puppet) startSyncing() {
|
||||
if !p.bridge.Config.Bridge.SyncWithCustomPuppets {
|
||||
return
|
||||
}
|
||||
|
||||
go func() {
|
||||
p.log.Debugln("Starting syncing...")
|
||||
p.customIntent.SyncPresence = "offline"
|
||||
|
||||
err := p.customIntent.Sync()
|
||||
if err != nil {
|
||||
p.log.Errorln("Fatal error syncing:", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (p *Puppet) stopSyncing() {
|
||||
if !p.bridge.Config.Bridge.SyncWithCustomPuppets {
|
||||
return
|
||||
}
|
||||
|
||||
p.customIntent.StopSync()
|
||||
}
|
||||
|
||||
func (p *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) {
|
||||
_, homeserver, _ := mxid.Parse()
|
||||
|
||||
p.log.Debugfln("Logging into %s with shared secret", mxid)
|
||||
|
||||
mac := hmac.New(sha512.New, []byte(p.bridge.Config.Bridge.LoginSharedSecretMap[homeserver]))
|
||||
mac.Write([]byte(mxid))
|
||||
|
||||
client, err := p.bridge.newDoublePuppetClient(mxid, "")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create mautrix client to log in: %v", err)
|
||||
}
|
||||
|
||||
resp, err := client.Login(&mautrix.ReqLogin{
|
||||
Type: mautrix.AuthTypePassword,
|
||||
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(mxid)},
|
||||
Password: hex.EncodeToString(mac.Sum(nil)),
|
||||
DeviceID: "Discord Bridge",
|
||||
InitialDeviceDisplayName: "Discord Bridge",
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return resp.AccessToken, nil
|
||||
}
|
||||
|
||||
func (p *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
|
||||
prevCustomMXID := p.CustomMXID
|
||||
if p.customIntent != nil {
|
||||
p.stopSyncing()
|
||||
}
|
||||
|
||||
p.CustomMXID = mxid
|
||||
p.AccessToken = accessToken
|
||||
|
||||
err := p.StartCustomMXID(false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if prevCustomMXID != "" {
|
||||
delete(p.bridge.puppetsByCustomMXID, prevCustomMXID)
|
||||
}
|
||||
|
||||
if p.CustomMXID != "" {
|
||||
p.bridge.puppetsByCustomMXID[p.CustomMXID] = p
|
||||
}
|
||||
|
||||
p.EnablePresence = p.bridge.Config.Bridge.DefaultBridgePresence
|
||||
p.EnableReceipts = p.bridge.Config.Bridge.DefaultBridgeReceipts
|
||||
|
||||
p.bridge.as.StateStore.MarkRegistered(p.CustomMXID)
|
||||
|
||||
p.Update()
|
||||
|
||||
// TODO leave rooms with default puppet
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -232,11 +232,16 @@ func (p *Portal) createMatrixRoom(user *User, channel *discordgo.Channel) error
|
||||
p.bridge.portalsByMXID[p.MXID] = p
|
||||
p.bridge.portalsLock.Unlock()
|
||||
|
||||
p.log.Debugln("inviting user", user)
|
||||
p.ensureUserInvited(user)
|
||||
user.syncChatDoublePuppetDetails(p, true)
|
||||
|
||||
p.syncParticipants(user, channel.Recipients)
|
||||
|
||||
if p.IsPrivateChat() {
|
||||
p.syncParticipants(user, channel.Recipients)
|
||||
puppet := user.bridge.GetPuppetByID(p.Key.Receiver)
|
||||
|
||||
chats := map[id.UserID][]id.RoomID{puppet.MXID: {p.MXID}}
|
||||
user.updateDirectChats(chats)
|
||||
}
|
||||
|
||||
firstEventResp, err := p.MainIntent().SendMessageEvent(p.MXID, portalCreationDummyEvent, struct{}{})
|
||||
|
||||
@@ -22,6 +22,9 @@ type Puppet struct {
|
||||
|
||||
MXID id.UserID
|
||||
|
||||
customIntent *appservice.IntentAPI
|
||||
customUser *User
|
||||
|
||||
syncLock sync.Mutex
|
||||
}
|
||||
|
||||
@@ -85,6 +88,59 @@ func (b *Bridge) GetPuppetByID(id string) *Puppet {
|
||||
return puppet
|
||||
}
|
||||
|
||||
func (b *Bridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
|
||||
b.puppetsLock.Lock()
|
||||
defer b.puppetsLock.Unlock()
|
||||
|
||||
puppet, ok := b.puppetsByCustomMXID[mxid]
|
||||
if !ok {
|
||||
dbPuppet := b.db.Puppet.GetByCustomMXID(mxid)
|
||||
if dbPuppet == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
puppet = b.NewPuppet(dbPuppet)
|
||||
b.puppets[puppet.ID] = puppet
|
||||
b.puppetsByCustomMXID[puppet.CustomMXID] = puppet
|
||||
}
|
||||
|
||||
return puppet
|
||||
}
|
||||
|
||||
func (b *Bridge) GetAllPuppetsWithCustomMXID() []*Puppet {
|
||||
return b.dbPuppetsToPuppets(b.db.Puppet.GetAllWithCustomMXID())
|
||||
}
|
||||
|
||||
func (b *Bridge) GetAllPuppets() []*Puppet {
|
||||
return b.dbPuppetsToPuppets(b.db.Puppet.GetAll())
|
||||
}
|
||||
|
||||
func (b *Bridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
|
||||
b.puppetsLock.Lock()
|
||||
defer b.puppetsLock.Unlock()
|
||||
|
||||
output := make([]*Puppet, len(dbPuppets))
|
||||
for index, dbPuppet := range dbPuppets {
|
||||
if dbPuppet == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
puppet, ok := b.puppets[dbPuppet.ID]
|
||||
if !ok {
|
||||
puppet = b.NewPuppet(dbPuppet)
|
||||
b.puppets[dbPuppet.ID] = puppet
|
||||
|
||||
if dbPuppet.CustomMXID != "" {
|
||||
b.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
|
||||
}
|
||||
}
|
||||
|
||||
output[index] = puppet
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
func (b *Bridge) FormatPuppetMXID(did string) id.UserID {
|
||||
return id.NewUserID(
|
||||
b.Config.Bridge.FormatUsername(did),
|
||||
@@ -97,8 +153,15 @@ func (p *Puppet) DefaultIntent() *appservice.IntentAPI {
|
||||
}
|
||||
|
||||
func (p *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
|
||||
// TODO: when we add double puppeting we need to adjust this.
|
||||
return p.DefaultIntent()
|
||||
if p.customIntent == nil || portal.Key.Receiver == p.ID {
|
||||
return p.DefaultIntent()
|
||||
}
|
||||
|
||||
return p.customIntent
|
||||
}
|
||||
|
||||
func (p *Puppet) CustomIntent() *appservice.IntentAPI {
|
||||
return p.customIntent
|
||||
}
|
||||
|
||||
func (p *Puppet) updatePortalMeta(meta func(portal *Portal)) {
|
||||
|
||||
163
bridge/user.go
163
bridge/user.go
@@ -3,6 +3,7 @@ package bridge
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -123,12 +124,19 @@ func (b *Bridge) startUsers() {
|
||||
b.log.Debugln("Starting users")
|
||||
|
||||
for _, user := range b.getAllUsers() {
|
||||
// if user.ID != "" {
|
||||
// haveSessions = true
|
||||
// }
|
||||
|
||||
go user.Connect()
|
||||
}
|
||||
|
||||
b.log.Debugln("Starting custom puppets")
|
||||
for _, customPuppet := range b.GetAllPuppetsWithCustomMXID() {
|
||||
go func(puppet *Puppet) {
|
||||
b.log.Debugln("Starting custom puppet", puppet.CustomMXID)
|
||||
|
||||
if err := puppet.StartCustomMXID(true); err != nil {
|
||||
puppet.log.Errorln("Failed to start custom puppet:", err)
|
||||
}
|
||||
}(customPuppet)
|
||||
}
|
||||
}
|
||||
|
||||
func (u *User) SetManagementRoom(roomID id.RoomID) {
|
||||
@@ -190,6 +198,53 @@ func (u *User) uploadQRCode(code string) (id.ContentURI, error) {
|
||||
return resp.ContentURI, nil
|
||||
}
|
||||
|
||||
func (u *User) tryAutomaticDoublePuppeting() {
|
||||
u.Lock()
|
||||
defer u.Unlock()
|
||||
|
||||
if !u.bridge.Config.CanAutoDoublePuppet(u.MXID) {
|
||||
return
|
||||
}
|
||||
|
||||
u.log.Debugln("Checking if double puppeting needs to be enabled")
|
||||
|
||||
puppet := u.bridge.GetPuppetByID(u.ID)
|
||||
if puppet.CustomMXID != "" {
|
||||
u.log.Debugln("User already has double-puppeting enabled")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
accessToken, err := puppet.loginWithSharedSecret(u.MXID)
|
||||
if err != nil {
|
||||
u.log.Warnln("Failed to login with shared secret:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
err = puppet.SwitchCustomMXID(accessToken, u.MXID)
|
||||
if err != nil {
|
||||
puppet.log.Warnln("Failed to switch to auto-logined custom puppet:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
u.log.Infoln("Successfully automatically enabled custom puppet")
|
||||
}
|
||||
|
||||
func (u *User) syncChatDoublePuppetDetails(portal *Portal, justCreated bool) {
|
||||
doublePuppet := portal.bridge.GetPuppetByCustomMXID(u.MXID)
|
||||
if doublePuppet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if doublePuppet == nil || doublePuppet.CustomIntent() == nil || portal.MXID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO sync mute status
|
||||
}
|
||||
|
||||
func (u *User) Login(token string) error {
|
||||
if token == "" {
|
||||
return fmt.Errorf("No token specified")
|
||||
@@ -216,6 +271,14 @@ func (u *User) Logout() error {
|
||||
return ErrNotLoggedIn
|
||||
}
|
||||
|
||||
puppet := u.bridge.GetPuppetByID(u.ID)
|
||||
if puppet.CustomMXID != "" {
|
||||
err := puppet.SwitchCustomMXID("", "")
|
||||
if err != nil {
|
||||
u.log.Warnln("Failed to logout-matrix while logging out of Discord:", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := u.Session.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -299,6 +362,8 @@ func (u *User) Disconnect() error {
|
||||
|
||||
func (u *User) connectedHandler(s *discordgo.Session, c *discordgo.Connect) {
|
||||
u.log.Debugln("connected to discord")
|
||||
|
||||
u.tryAutomaticDoublePuppeting()
|
||||
}
|
||||
|
||||
func (u *User) disconnectedHandler(s *discordgo.Session, d *discordgo.Disconnect) {
|
||||
@@ -447,6 +512,11 @@ func (u *User) ensureInvited(intent *appservice.IntentAPI, roomID id.RoomID, isD
|
||||
Raw: map[string]interface{}{},
|
||||
}
|
||||
|
||||
customPuppet := u.bridge.GetPuppetByCustomMXID(u.MXID)
|
||||
if customPuppet != nil && customPuppet.CustomIntent() != nil {
|
||||
inviteContent.Raw["fi.mau.will_auto_accept"] = true
|
||||
}
|
||||
|
||||
_, err := intent.SendStateEvent(roomID, event.StateMember, u.MXID.String(), &inviteContent)
|
||||
|
||||
var httpErr mautrix.HTTPError
|
||||
@@ -459,5 +529,90 @@ func (u *User) ensureInvited(intent *appservice.IntentAPI, roomID id.RoomID, isD
|
||||
ret = true
|
||||
}
|
||||
|
||||
if customPuppet != nil && customPuppet.CustomIntent() != nil {
|
||||
err = customPuppet.CustomIntent().EnsureJoined(roomID, appservice.EnsureJoinedParams{IgnoreCache: true})
|
||||
if err != nil {
|
||||
u.log.Warnfln("Failed to auto-join %s: %v", roomID, err)
|
||||
ret = false
|
||||
} else {
|
||||
ret = true
|
||||
}
|
||||
}
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (u *User) getDirectChats() map[id.UserID][]id.RoomID {
|
||||
chats := map[id.UserID][]id.RoomID{}
|
||||
|
||||
privateChats := u.bridge.db.Portal.FindPrivateChats(u.ID)
|
||||
for _, portal := range privateChats {
|
||||
if portal.MXID != "" {
|
||||
puppetMXID := u.bridge.FormatPuppetMXID(portal.Key.Receiver)
|
||||
|
||||
chats[puppetMXID] = []id.RoomID{portal.MXID}
|
||||
}
|
||||
}
|
||||
|
||||
return chats
|
||||
}
|
||||
|
||||
func (u *User) updateDirectChats(chats map[id.UserID][]id.RoomID) {
|
||||
if !u.bridge.Config.Bridge.SyncDirectChatList {
|
||||
return
|
||||
}
|
||||
|
||||
puppet := u.bridge.GetPuppetByMXID(u.MXID)
|
||||
if puppet == nil {
|
||||
return
|
||||
}
|
||||
|
||||
intent := puppet.CustomIntent()
|
||||
if intent == nil {
|
||||
return
|
||||
}
|
||||
|
||||
method := http.MethodPatch
|
||||
if chats == nil {
|
||||
chats = u.getDirectChats()
|
||||
method = http.MethodPut
|
||||
}
|
||||
|
||||
u.log.Debugln("Updating m.direct list on homeserver")
|
||||
|
||||
var err error
|
||||
if u.bridge.Config.Homeserver.Asmux {
|
||||
urlPath := intent.BuildBaseURL("_matrix", "client", "unstable", "com.beeper.asmux", "dms")
|
||||
_, err = intent.MakeFullRequest(mautrix.FullRequest{
|
||||
Method: method,
|
||||
URL: urlPath,
|
||||
Headers: http.Header{"X-Asmux-Auth": {u.bridge.as.Registration.AppToken}},
|
||||
RequestJSON: chats,
|
||||
})
|
||||
} else {
|
||||
existingChats := map[id.UserID][]id.RoomID{}
|
||||
|
||||
err = intent.GetAccountData(event.AccountDataDirectChats.Type, &existingChats)
|
||||
if err != nil {
|
||||
u.log.Warnln("Failed to get m.direct list to update it:", err)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
for userID, rooms := range existingChats {
|
||||
if _, ok := u.bridge.ParsePuppetMXID(userID); !ok {
|
||||
// This is not a ghost user, include it in the new list
|
||||
chats[userID] = rooms
|
||||
} else if _, ok := chats[userID]; !ok && method == http.MethodPatch {
|
||||
// This is a ghost user, but we're not replacing the whole list, so include it too
|
||||
chats[userID] = rooms
|
||||
}
|
||||
}
|
||||
|
||||
err = intent.SetAccountData(event.AccountDataDirectChats.Type, &chats)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
u.log.Warnln("Failed to update m.direct list:", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user