puppet.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package bridge
  2. import (
  3. "fmt"
  4. "regexp"
  5. log "maunium.net/go/maulogger/v2"
  6. "maunium.net/go/mautrix/appservice"
  7. "maunium.net/go/mautrix/id"
  8. "gitlab.com/beeper/discord/database"
  9. )
  10. type Puppet struct {
  11. *database.Puppet
  12. bridge *Bridge
  13. log log.Logger
  14. MXID id.UserID
  15. }
  16. var userIDRegex *regexp.Regexp
  17. func (b *Bridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  18. return &Puppet{
  19. Puppet: dbPuppet,
  20. bridge: b,
  21. log: b.log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.ID)),
  22. MXID: b.FormatPuppetMXID(dbPuppet.ID),
  23. }
  24. }
  25. func (b *Bridge) ParsePuppetMXID(mxid id.UserID) (string, bool) {
  26. if userIDRegex == nil {
  27. pattern := fmt.Sprintf(
  28. "^@%s:%s$",
  29. b.config.Bridge.FormatUsername("([0-9]+)"),
  30. b.config.Homeserver.Domain,
  31. )
  32. userIDRegex = regexp.MustCompile(pattern)
  33. }
  34. match := userIDRegex.FindStringSubmatch(string(mxid))
  35. if len(match) == 2 {
  36. return match[1], true
  37. }
  38. return "", false
  39. }
  40. func (b *Bridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
  41. id, ok := b.ParsePuppetMXID(mxid)
  42. if !ok {
  43. return nil
  44. }
  45. return b.GetPuppetByID(id)
  46. }
  47. func (b *Bridge) GetPuppetByID(id string) *Puppet {
  48. b.puppetsLock.Lock()
  49. defer b.puppetsLock.Unlock()
  50. puppet, ok := b.puppets[id]
  51. if !ok {
  52. dbPuppet := b.db.Puppet.Get(id)
  53. if dbPuppet == nil {
  54. dbPuppet = b.db.Puppet.New()
  55. dbPuppet.ID = id
  56. dbPuppet.Insert()
  57. }
  58. puppet = b.NewPuppet(dbPuppet)
  59. b.puppets[puppet.ID] = puppet
  60. }
  61. return puppet
  62. }
  63. func (b *Bridge) FormatPuppetMXID(did string) id.UserID {
  64. return id.NewUserID(
  65. b.config.Bridge.FormatUsername(did),
  66. b.config.Homeserver.Domain,
  67. )
  68. }
  69. func (p *Puppet) DefaultIntent() *appservice.IntentAPI {
  70. return p.bridge.as.Intent(p.MXID)
  71. }