portal.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package bridge
  2. import (
  3. "fmt"
  4. log "maunium.net/go/maulogger/v2"
  5. "maunium.net/go/mautrix/event"
  6. "maunium.net/go/mautrix/id"
  7. "gitlab.com/beeper/discord/database"
  8. )
  9. type PortalMatrixMessage struct {
  10. evt *event.Event
  11. user *User
  12. }
  13. type Portal struct {
  14. *database.Portal
  15. bridge *Bridge
  16. log log.Logger
  17. matrixMessages chan PortalMatrixMessage
  18. }
  19. func (b *Bridge) loadPortal(dbPortal *database.Portal, key *database.PortalKey) *Portal {
  20. // If we weren't given a portal we'll attempt to create it if a key was
  21. // provided.
  22. if dbPortal == nil {
  23. if key == nil {
  24. return nil
  25. }
  26. dbPortal = b.db.Portal.New()
  27. dbPortal.Key = *key
  28. dbPortal.Insert()
  29. }
  30. portal := b.NewPortal(dbPortal)
  31. // No need to lock, it is assumed that our callers have already acquired
  32. // the lock.
  33. b.portalsByID[portal.Key] = portal
  34. if portal.MXID != "" {
  35. b.portalsByMXID[portal.MXID] = portal
  36. }
  37. return portal
  38. }
  39. func (b *Bridge) GetPortalByMXID(mxid id.RoomID) *Portal {
  40. b.portalsLock.Lock()
  41. defer b.portalsLock.Unlock()
  42. portal, ok := b.portalsByMXID[mxid]
  43. if !ok {
  44. return b.loadPortal(b.db.Portal.GetByMXID(mxid), nil)
  45. }
  46. return portal
  47. }
  48. func (b *Bridge) NewPortal(dbPortal *database.Portal) *Portal {
  49. portal := &Portal{
  50. Portal: dbPortal,
  51. bridge: b,
  52. log: b.log.Sub(fmt.Sprintf("Portal/%s", dbPortal.Key)),
  53. matrixMessages: make(chan PortalMatrixMessage, b.config.Bridge.PortalMessageBuffer),
  54. }
  55. go portal.messageLoop()
  56. return portal
  57. }
  58. func (p *Portal) HandleMatrixInvite(sender *User, evt *event.Event) {
  59. // Look up an existing puppet or create a new one.
  60. puppet := p.bridge.GetPuppetByMXID(id.UserID(evt.GetStateKey()))
  61. if puppet != nil {
  62. p.log.Infoln("no puppet for %v", sender)
  63. // Open a conversation on the discord side?
  64. }
  65. p.log.Infoln("puppet:", puppet)
  66. }
  67. func (p *Portal) messageLoop() {
  68. for {
  69. select {
  70. case msg := <-p.matrixMessages:
  71. p.log.Infoln("got message", msg)
  72. }
  73. }
  74. }