puppet.go 1.5 KB

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