They mostly work including display names and avatars. However that's about all they do right now.
357 lines
8.1 KiB
Go
357 lines
8.1 KiB
Go
package bridge
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
|
log "maunium.net/go/maulogger/v2"
|
|
"maunium.net/go/mautrix"
|
|
"maunium.net/go/mautrix/appservice"
|
|
"maunium.net/go/mautrix/event"
|
|
"maunium.net/go/mautrix/id"
|
|
|
|
"gitlab.com/beeper/discord/database"
|
|
)
|
|
|
|
type portalDiscordMessage struct {
|
|
msg interface{}
|
|
user *User
|
|
}
|
|
|
|
type portalMatrixMessage struct {
|
|
evt *event.Event
|
|
user *User
|
|
}
|
|
|
|
type Portal struct {
|
|
*database.Portal
|
|
|
|
bridge *Bridge
|
|
log log.Logger
|
|
|
|
channel *discordgo.Channel
|
|
|
|
roomCreateLock sync.Mutex
|
|
|
|
discordMessages chan portalDiscordMessage
|
|
matrixMessages chan portalMatrixMessage
|
|
}
|
|
|
|
var (
|
|
portalCreationDummyEvent = event.Type{Type: "fi.mau.dummy.portal_created", Class: event.MessageEventType}
|
|
)
|
|
|
|
func (b *Bridge) loadPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
|
|
// If we weren't given a portal we'll attempt to create it if a key was
|
|
// provided.
|
|
if dbPortal == nil {
|
|
if key == nil {
|
|
return nil
|
|
}
|
|
|
|
dbPortal = b.db.Portal.New()
|
|
dbPortal.Key = *key
|
|
dbPortal.Insert()
|
|
}
|
|
|
|
portal := b.NewPortal(dbPortal)
|
|
|
|
// No need to lock, it is assumed that our callers have already acquired
|
|
// the lock.
|
|
b.portalsByID[portal.Key] = portal
|
|
if portal.MXID != "" {
|
|
b.portalsByMXID[portal.MXID] = portal
|
|
}
|
|
|
|
return portal
|
|
}
|
|
|
|
func (b *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
|
|
b.portalsLock.Lock()
|
|
defer b.portalsLock.Unlock()
|
|
|
|
portal, ok := b.portalsByMXID[mxid]
|
|
if !ok {
|
|
return b.loadPortal(b.db.Portal.GetByMXID(mxid), nil)
|
|
}
|
|
|
|
return portal
|
|
}
|
|
|
|
func (b *Bridge) GetPortalByID(key database.PortalKey) *Portal {
|
|
b.portalsLock.Lock()
|
|
defer b.portalsLock.Unlock()
|
|
|
|
portal, ok := b.portalsByID[key]
|
|
if !ok {
|
|
return b.loadPortal(b.db.Portal.GetByID(key), &key)
|
|
}
|
|
|
|
return portal
|
|
}
|
|
|
|
func (b *Bridge) GetAllPortals() []*Portal {
|
|
return b.dbPortalsToPortals(b.db.Portal.GetAll())
|
|
}
|
|
|
|
func (b *Bridge) GetAllPortalsByID(id string) []*Portal {
|
|
return b.dbPortalsToPortals(b.db.Portal.GetAllByID(id))
|
|
}
|
|
|
|
func (b *Bridge) dbPortalsToPortals(dbPortals []*database.Portal) []*Portal {
|
|
b.portalsLock.Lock()
|
|
defer b.portalsLock.Unlock()
|
|
|
|
output := make([]*Portal, len(dbPortals))
|
|
for index, dbPortal := range dbPortals {
|
|
if dbPortal == nil {
|
|
continue
|
|
}
|
|
|
|
portal, ok := b.portalsByID[dbPortal.Key]
|
|
if !ok {
|
|
portal = b.loadPortal(dbPortal, nil)
|
|
}
|
|
|
|
output[index] = portal
|
|
}
|
|
|
|
return output
|
|
}
|
|
|
|
func (b *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
|
|
portal := &Portal{
|
|
Portal: dbPortal,
|
|
bridge: b,
|
|
log: b.log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
|
|
|
|
discordMessages: make(chan portalDiscordMessage, b.Config.Bridge.PortalMessageBuffer),
|
|
matrixMessages: make(chan portalMatrixMessage, b.Config.Bridge.PortalMessageBuffer),
|
|
}
|
|
|
|
go portal.messageLoop()
|
|
|
|
return portal
|
|
}
|
|
|
|
func (p *Portal) HandleMatrixInvite(sender *User, evt *event.Event) {
|
|
// Look up an existing puppet or create a new one.
|
|
puppet := p.bridge.GetPuppetByMXID(id.UserID(evt.GetStateKey()))
|
|
if puppet != nil {
|
|
p.log.Infoln("no puppet for %v", sender)
|
|
// Open a conversation on the discord side?
|
|
}
|
|
p.log.Infoln("puppet:", puppet)
|
|
}
|
|
|
|
func (p *Portal) messageLoop() {
|
|
for {
|
|
select {
|
|
case msg := <-p.matrixMessages:
|
|
p.handleMatrixMessages(msg)
|
|
case msg := <-p.discordMessages:
|
|
p.handleDiscordMessages(msg)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *Portal) IsPrivateChat() bool {
|
|
if p.channel != nil {
|
|
return p.channel.Type == discordgo.ChannelTypeDM
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func (p *Portal) MainIntent() *appservice.IntentAPI {
|
|
if p.IsPrivateChat() && p.channel != nil && len(p.channel.Recipients) == 1 {
|
|
return p.bridge.GetPuppetByID(p.channel.Recipients[0].ID).DefaultIntent()
|
|
}
|
|
|
|
return p.bridge.bot
|
|
}
|
|
|
|
func (p *Portal) getMessagePuppet(user *User, message *discordgo.Message) *Puppet {
|
|
p.log.Debugf("getMessagePuppet")
|
|
if message.Author.ID == user.ID {
|
|
return p.bridge.GetPuppetByID(user.ID)
|
|
}
|
|
|
|
puppet := p.bridge.GetPuppetByID(message.Author.ID)
|
|
puppet.SyncContact(user)
|
|
|
|
return puppet
|
|
}
|
|
|
|
func (p *Portal) getMessageIntent(user *User, message *discordgo.Message) *appservice.IntentAPI {
|
|
return p.getMessagePuppet(user, message).IntentFor(p)
|
|
}
|
|
|
|
func (p *Portal) createMatrixRoom(user *User, channel *discordgo.Channel) error {
|
|
p.channel = channel
|
|
|
|
p.roomCreateLock.Lock()
|
|
defer p.roomCreateLock.Unlock()
|
|
|
|
// If we have a matrix id the room should exist so we have nothing to do.
|
|
if p.MXID != "" {
|
|
return nil
|
|
}
|
|
|
|
intent := p.MainIntent()
|
|
if err := intent.EnsureRegistered(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// if p.IsPrivateChat() {
|
|
p.Name = channel.Name
|
|
p.Topic = channel.Topic
|
|
|
|
// TODO: get avatars figured out
|
|
// p.Avatar = puppet.Avatar
|
|
// p.AvatarURL = puppet.AvatarURL
|
|
// }
|
|
|
|
p.log.Infoln("Creating Matrix room for channel:", p.Portal.Key.ChannelID)
|
|
|
|
initialState := []*event.Event{}
|
|
|
|
creationContent := make(map[string]interface{})
|
|
// if !portal.bridge.Config.Bridge.FederateRooms {
|
|
creationContent["m.federate"] = false
|
|
// }
|
|
|
|
var invite []id.UserID
|
|
|
|
if p.IsPrivateChat() {
|
|
invite = append(invite, p.bridge.bot.UserID)
|
|
}
|
|
|
|
resp, err := intent.CreateRoom(&mautrix.ReqCreateRoom{
|
|
Visibility: "private",
|
|
Name: p.Name,
|
|
Topic: p.Topic,
|
|
Preset: "private_chat",
|
|
IsDirect: p.IsPrivateChat(),
|
|
InitialState: initialState,
|
|
CreationContent: creationContent,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
p.MXID = resp.RoomID
|
|
p.Update()
|
|
p.bridge.portalsLock.Lock()
|
|
p.bridge.portalsByMXID[p.MXID] = p
|
|
p.bridge.portalsLock.Unlock()
|
|
|
|
p.log.Debugln("inviting user", user)
|
|
p.ensureUserInvited(user)
|
|
|
|
if p.IsPrivateChat() {
|
|
p.syncParticipants(user, channel.Recipients)
|
|
}
|
|
|
|
firstEventResp, err := p.MainIntent().SendMessageEvent(p.MXID, portalCreationDummyEvent, struct{}{})
|
|
if err != nil {
|
|
p.log.Errorln("Failed to send dummy event to mark portal creation:", err)
|
|
} else {
|
|
p.FirstEventID = firstEventResp.EventID
|
|
p.Update()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (p *Portal) handleDiscordMessages(msg portalDiscordMessage) {
|
|
if p.MXID == "" {
|
|
p.log.Debugln("Creating Matrix room from incoming message")
|
|
|
|
discordMsg := msg.msg.(*discordgo.MessageCreate)
|
|
channel, err := msg.user.Session.Channel(discordMsg.ChannelID)
|
|
if err != nil {
|
|
p.log.Errorln("Failed to find channel for message:", err)
|
|
|
|
return
|
|
}
|
|
|
|
if err := p.createMatrixRoom(msg.user, channel); err != nil {
|
|
p.log.Errorln("Failed to create portal room:", err)
|
|
|
|
return
|
|
}
|
|
}
|
|
|
|
switch msg.msg.(type) {
|
|
case *discordgo.MessageCreate:
|
|
p.handleDiscordMessage(msg.msg.(*discordgo.MessageCreate).Message)
|
|
default:
|
|
p.log.Warnln("unknown message type")
|
|
}
|
|
}
|
|
|
|
func (p *Portal) ensureUserInvited(user *User) bool {
|
|
return user.ensureInvited(p.MainIntent(), p.MXID, p.IsPrivateChat())
|
|
}
|
|
|
|
func (p *Portal) handleDiscordMessage(msg *discordgo.Message) {
|
|
if p.MXID == "" {
|
|
p.log.Warnln("handle message called without a valid portal")
|
|
return
|
|
}
|
|
|
|
// TODO: Check if we already got the message
|
|
content := &event.MessageEventContent{
|
|
Body: msg.Content,
|
|
MsgType: event.MsgText,
|
|
}
|
|
|
|
resp, err := p.MainIntent().SendMessageEvent(p.MXID, event.EventMessage, content)
|
|
p.log.Warnln("response:", resp)
|
|
p.log.Warnln("error:", err)
|
|
}
|
|
|
|
func (p *Portal) syncParticipants(source *User, participants []*discordgo.User) {
|
|
for _, participant := range participants {
|
|
puppet := p.bridge.GetPuppetByID(participant.ID)
|
|
puppet.SyncContact(source)
|
|
|
|
user := p.bridge.GetUserByID(participant.ID)
|
|
if user != nil {
|
|
p.ensureUserInvited(user)
|
|
}
|
|
|
|
if user == nil || !puppet.IntentFor(p).IsCustomPuppet {
|
|
if err := puppet.IntentFor(p).EnsureJoined(p.MXID); err != nil {
|
|
p.log.Warnfln("Failed to make puppet of %s join %s: %v", participant.ID, p.MXID, err)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *Portal) handleMatrixMessages(msg portalMatrixMessage) {
|
|
switch msg.evt.Type {
|
|
case event.EventMessage:
|
|
p.handleMatrixMessage(msg.user, msg.evt)
|
|
}
|
|
}
|
|
|
|
func (p *Portal) handleMatrixMessage(sender *User, evt *event.Event) {
|
|
if p.IsPrivateChat() && sender.ID != p.Key.Receiver {
|
|
return
|
|
}
|
|
|
|
content, ok := evt.Content.Parsed.(*event.MessageEventContent)
|
|
if !ok {
|
|
p.log.Debugfln("Failed to handle event %s: unexpected parsed content type %T", evt.ID, evt.Content.Parsed)
|
|
|
|
return
|
|
}
|
|
|
|
sender.Session.ChannelMessageSend(p.Key.ChannelID, content.Body)
|
|
p.log.Debugln("sent message:", content.Body)
|
|
}
|