Compare commits
2 Commits
megabridge
...
discord-br
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89ac3632ec | ||
|
|
30752fa48b |
@@ -61,6 +61,7 @@ func (dc *DiscordClient) FetchMessages(ctx context.Context, fetchParams bridgev2
|
||||
log.Debug().Msg("Fetching channel history for backfill")
|
||||
msgs, err := dc.Session.ChannelMessages(channelID, count, beforeID, afterID, "")
|
||||
if err != nil {
|
||||
dc.handlePossible40002(err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
153
pkg/connector/bridge_state.go
Normal file
153
pkg/connector/bridge_state.go
Normal file
@@ -0,0 +1,153 @@
|
||||
// mautrix-discord - A Matrix-Discord puppeting bridge.
|
||||
// Copyright (C) 2026 Tulir Asokan
|
||||
//
|
||||
// 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 connector
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/bwmarrin/discordgo"
|
||||
"maunium.net/go/mautrix/bridgev2/status"
|
||||
)
|
||||
|
||||
const (
|
||||
DiscordNotLoggedIn status.BridgeStateErrorCode = "dc-not-logged-in"
|
||||
DiscordTransientDisconnect status.BridgeStateErrorCode = "dc-transient-disconnect"
|
||||
DiscordInvalidAuth status.BridgeStateErrorCode = "dc-websocket-disconnect-4004"
|
||||
DiscordHTTP40002 status.BridgeStateErrorCode = "dc-http-40002"
|
||||
DiscordUnknownWebsocketErr status.BridgeStateErrorCode = "dc-unknown-websocket-error"
|
||||
)
|
||||
|
||||
const discordDisconnectDebounce = 7 * time.Second
|
||||
|
||||
func init() {
|
||||
status.BridgeStateHumanErrors.Update(status.BridgeStateErrorMap{
|
||||
DiscordNotLoggedIn: "You're not logged into Discord. Relogin to continue using the bridge.",
|
||||
DiscordTransientDisconnect: "Temporarily disconnected from Discord, trying to reconnect.",
|
||||
DiscordInvalidAuth: "Discord access token is no longer valid, please log in again.",
|
||||
DiscordHTTP40002: "Discord requires a verified account, please verify and log in again.",
|
||||
DiscordUnknownWebsocketErr: "Unknown Discord websocket error.",
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DiscordClient) resetBridgeStateTracking() {
|
||||
d.bridgeStateLock.Lock()
|
||||
if d.disconnectTimer != nil {
|
||||
d.disconnectTimer.Stop()
|
||||
d.disconnectTimer = nil
|
||||
}
|
||||
d.invalidAuthDetected = false
|
||||
d.bridgeStateLock.Unlock()
|
||||
}
|
||||
|
||||
func (d *DiscordClient) markConnected() {
|
||||
if d.UserLogin == nil {
|
||||
return
|
||||
}
|
||||
d.bridgeStateLock.Lock()
|
||||
if d.disconnectTimer != nil {
|
||||
d.disconnectTimer.Stop()
|
||||
d.disconnectTimer = nil
|
||||
}
|
||||
d.invalidAuthDetected = false
|
||||
d.bridgeStateLock.Unlock()
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{StateEvent: status.StateConnected})
|
||||
}
|
||||
|
||||
func (d *DiscordClient) markInvalidAuth(message string) {
|
||||
if d.UserLogin == nil {
|
||||
return
|
||||
}
|
||||
d.bridgeStateLock.Lock()
|
||||
d.invalidAuthDetected = true
|
||||
if d.disconnectTimer != nil {
|
||||
d.disconnectTimer.Stop()
|
||||
d.disconnectTimer = nil
|
||||
}
|
||||
d.bridgeStateLock.Unlock()
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: DiscordInvalidAuth,
|
||||
Message: message,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DiscordClient) scheduleTransientDisconnect(message string) {
|
||||
if d.UserLogin == nil {
|
||||
return
|
||||
}
|
||||
d.bridgeStateLock.Lock()
|
||||
if d.invalidAuthDetected {
|
||||
d.bridgeStateLock.Unlock()
|
||||
return
|
||||
}
|
||||
if d.disconnectTimer != nil {
|
||||
d.disconnectTimer.Stop()
|
||||
}
|
||||
login := d.UserLogin
|
||||
d.disconnectTimer = time.AfterFunc(discordDisconnectDebounce, func() {
|
||||
d.bridgeStateLock.Lock()
|
||||
d.disconnectTimer = nil
|
||||
invalidAuth := d.invalidAuthDetected
|
||||
d.bridgeStateLock.Unlock()
|
||||
if invalidAuth {
|
||||
return
|
||||
}
|
||||
login.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateTransientDisconnect,
|
||||
Error: DiscordTransientDisconnect,
|
||||
Message: message,
|
||||
})
|
||||
})
|
||||
d.bridgeStateLock.Unlock()
|
||||
}
|
||||
|
||||
func (d *DiscordClient) sendConnectFailure(err error, final bool) {
|
||||
if d.UserLogin == nil || err == nil {
|
||||
return
|
||||
}
|
||||
stateEvent := status.StateTransientDisconnect
|
||||
if final {
|
||||
stateEvent = status.StateUnknownError
|
||||
}
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: stateEvent,
|
||||
Error: DiscordUnknownWebsocketErr,
|
||||
Message: err.Error(),
|
||||
Info: map[string]any{
|
||||
"go_error": err.Error(),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DiscordClient) handlePossible40002(err error) bool {
|
||||
var restErr *discordgo.RESTError
|
||||
if !errors.As(err, &restErr) || restErr.Message == nil || restErr.Message.Code != discordgo.ErrCodeActionRequiredVerifiedAccount {
|
||||
return false
|
||||
}
|
||||
if d.UserLogin == nil {
|
||||
return true
|
||||
}
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: DiscordHTTP40002,
|
||||
Message: restErr.Message.Message,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
return true
|
||||
}
|
||||
@@ -48,6 +48,10 @@ type DiscordClient struct {
|
||||
|
||||
markedOpened map[string]time.Time
|
||||
markedOpenedLock sync.Mutex
|
||||
|
||||
bridgeStateLock sync.Mutex
|
||||
disconnectTimer *time.Timer
|
||||
invalidAuthDetected bool
|
||||
}
|
||||
|
||||
func (d *DiscordConnector) LoadUserLogin(ctx context.Context, login *bridgev2.UserLogin) error {
|
||||
@@ -95,6 +99,7 @@ func (d *DiscordClient) SetUp(ctx context.Context, meta *discordid.UserLoginMeta
|
||||
}
|
||||
|
||||
d.markedOpened = make(map[string]time.Time)
|
||||
d.resetBridgeStateTracking()
|
||||
}
|
||||
|
||||
func (d *DiscordClient) Connect(ctx context.Context) {
|
||||
@@ -104,7 +109,8 @@ func (d *DiscordClient) Connect(ctx context.Context) {
|
||||
log.Error().Msg("No session present")
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateBadCredentials,
|
||||
Error: "discord-not-logged-in",
|
||||
Error: DiscordNotLoggedIn,
|
||||
UserAction: status.UserActionRelogin,
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -112,9 +118,7 @@ func (d *DiscordClient) Connect(ctx context.Context) {
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateConnecting,
|
||||
})
|
||||
if err := d.connect(ctx); err != nil {
|
||||
log.Err(err).Msg("Couldn't connect to Discord")
|
||||
}
|
||||
d.connectWithRetry(ctx, 0)
|
||||
}
|
||||
|
||||
func (cl *DiscordClient) handleDiscordEventSync(event any) {
|
||||
@@ -140,7 +144,9 @@ func (cl *DiscordClient) connect(ctx context.Context) error {
|
||||
|
||||
// Ensure that we actually have a user.
|
||||
if !cl.IsLoggedIn() {
|
||||
return fmt.Errorf("unknown identity even after connecting to Discord")
|
||||
err := fmt.Errorf("unknown identity even after connecting to Discord")
|
||||
log.Err(err).Msg("No Discord user available after connecting")
|
||||
return err
|
||||
}
|
||||
user := cl.Session.State.User
|
||||
log.Info().Str("user_id", user.ID).Str("user_username", user.Username).Msg("Connected to Discord")
|
||||
@@ -161,6 +167,27 @@ func (cl *DiscordClient) connect(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DiscordClient) connectWithRetry(ctx context.Context, retryCount int) {
|
||||
err := d.connect(ctx)
|
||||
if err == nil || ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if retryCount < 6 {
|
||||
d.sendConnectFailure(err, false)
|
||||
retryInSeconds := 2 << retryCount
|
||||
zerolog.Ctx(ctx).Debug().Int("retry_in_seconds", retryInSeconds).Msg("Sleeping and retrying connection")
|
||||
select {
|
||||
case <-time.After(time.Duration(retryInSeconds) * time.Second):
|
||||
case <-ctx.Done():
|
||||
zerolog.Ctx(ctx).Info().Msg("Context canceled, exiting connect retry loop")
|
||||
return
|
||||
}
|
||||
d.connectWithRetry(ctx, retryCount+1)
|
||||
} else {
|
||||
d.sendConnectFailure(err, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DiscordClient) Disconnect() {
|
||||
d.UserLogin.Log.Info().Msg("Disconnecting session")
|
||||
d.Session.Close()
|
||||
@@ -389,6 +416,7 @@ func (d *DiscordClient) bridgeGuild(ctx context.Context, guildID string) error {
|
||||
Threads: true,
|
||||
})
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Warn().Err(err).Msg("Failed to subscribe to guild; proceeding")
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/rs/zerolog"
|
||||
"maunium.net/go/mautrix/bridgev2"
|
||||
"maunium.net/go/mautrix/bridgev2/networkid"
|
||||
"maunium.net/go/mautrix/bridgev2/status"
|
||||
|
||||
"go.mau.fi/mautrix-discord/pkg/discordid"
|
||||
)
|
||||
@@ -196,16 +195,21 @@ func (d *DiscordClient) handleDiscordEvent(rawEvt any) {
|
||||
Logger()
|
||||
|
||||
switch evt := rawEvt.(type) {
|
||||
case *discordgo.Connect:
|
||||
log.Info().Msg("Discord gateway connected")
|
||||
d.markConnected()
|
||||
case *discordgo.Disconnect:
|
||||
log.Info().Msg("Discord gateway disconnected")
|
||||
d.scheduleTransientDisconnect("")
|
||||
case *discordgo.InvalidAuth:
|
||||
log.Warn().Msg("Discord gateway reported invalid auth")
|
||||
d.markInvalidAuth("You have been logged out of Discord, please reconnect")
|
||||
case *discordgo.Ready:
|
||||
log.Info().Msg("Received READY dispatch from discordgo")
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateConnected,
|
||||
})
|
||||
d.markConnected()
|
||||
case *discordgo.Resumed:
|
||||
log.Info().Msg("Received RESUMED dispatch from discordgo")
|
||||
d.UserLogin.BridgeState.Send(status.BridgeState{
|
||||
StateEvent: status.StateConnected,
|
||||
})
|
||||
d.markConnected()
|
||||
case *discordgo.MessageCreate:
|
||||
if evt.Author == nil {
|
||||
log.Trace().Int("message_type", int(evt.Message.Type)).
|
||||
|
||||
@@ -56,6 +56,7 @@ func (d *DiscordClient) HandleMatrixMessage(ctx context.Context, msg *bridgev2.M
|
||||
|
||||
sentMsg, err := d.Session.ChannelMessageSendComplex(discordid.ParsePortalID(msg.Portal.ID), sendReq, options...)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
return nil, err
|
||||
}
|
||||
sentMsgTimestamp, _ := discordgo.SnowflakeTimestamp(sentMsg.ID)
|
||||
@@ -90,6 +91,9 @@ func (d *DiscordClient) HandleMatrixReaction(ctx context.Context, reaction *brid
|
||||
meta := portal.Metadata.(*discordid.PortalMetadata)
|
||||
|
||||
err := d.Session.MessageReactionAddUser(meta.GuildID, discordid.ParsePortalID(portal.ID), discordid.ParseMessageID(reaction.TargetMessage.ID), relatesToKey)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -100,13 +104,20 @@ func (d *DiscordClient) HandleMatrixReactionRemove(ctx context.Context, removal
|
||||
guildID := removal.Portal.Metadata.(*discordid.PortalMetadata).GuildID
|
||||
|
||||
err := d.Session.MessageReactionRemoveUser(guildID, channelID, discordid.ParseMessageID(removing.MessageID), discordid.ParseEmojiID(emojiID), discordid.ParseUserLoginID(d.UserLogin.ID))
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DiscordClient) HandleMatrixMessageRemove(ctx context.Context, removal *bridgev2.MatrixMessageRemove) error {
|
||||
channelID := discordid.ParsePortalID(removal.Portal.ID)
|
||||
messageID := discordid.ParseMessageID(removal.TargetMessage.ID)
|
||||
return d.Session.ChannelMessageDelete(channelID, messageID)
|
||||
err := d.Session.ChannelMessageDelete(channelID, messageID)
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *DiscordClient) HandleMatrixReadReceipt(ctx context.Context, msg *bridgev2.MatrixReadReceipt) error {
|
||||
@@ -153,6 +164,7 @@ func (d *DiscordClient) HandleMatrixReadReceipt(ctx context.Context, msg *bridge
|
||||
channelID := discordid.ParsePortalID(msg.Portal.ID)
|
||||
resp, err := d.Session.ChannelMessageAckNoToken(channelID, targetMessageID, discordgo.WithChannelReferer(guildID, channelID))
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Err(err).Msg("Failed to send read receipt to Discord")
|
||||
return err
|
||||
} else if resp.Token != nil {
|
||||
@@ -186,6 +198,7 @@ func (d *DiscordClient) viewingChannel(ctx context.Context, portal *bridgev2.Por
|
||||
err := d.Session.MarkViewing(channelID)
|
||||
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Error().Err(err).Msg("Failed to mark user as viewing channel")
|
||||
return err
|
||||
}
|
||||
@@ -211,6 +224,7 @@ func (d *DiscordClient) HandleMatrixTyping(ctx context.Context, msg *bridgev2.Ma
|
||||
err := d.Session.ChannelTyping(channelID, discordgo.WithChannelReferer(guildID, channelID))
|
||||
|
||||
if err != nil {
|
||||
d.handlePossible40002(err)
|
||||
log.Warn().Err(err).Msg("Failed to mark user as typing")
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -97,6 +97,11 @@ func (dl *DiscordGenericLogin) FinalizeCreatingLogin(ctx context.Context, token
|
||||
Str("user_username", user.Username).
|
||||
Msg("Logged in to Discord")
|
||||
|
||||
// We already opened the gateway session before creating the UserLogin,
|
||||
// which means the initial READY/CONNECT event was dropped. Send Connected
|
||||
// here so infra gets login status for new logins.
|
||||
client.markConnected()
|
||||
|
||||
return ul, nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user