custompuppet.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "maunium.net/go/mautrix/id"
  4. )
  5. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
  6. puppet.CustomMXID = mxid
  7. puppet.AccessToken = accessToken
  8. puppet.Update()
  9. err := puppet.StartCustomMXID(false)
  10. if err != nil {
  11. return err
  12. }
  13. // TODO leave rooms with default puppet
  14. return nil
  15. }
  16. func (puppet *Puppet) ClearCustomMXID() {
  17. save := puppet.CustomMXID != "" || puppet.AccessToken != ""
  18. puppet.bridge.puppetsLock.Lock()
  19. if puppet.CustomMXID != "" && puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] == puppet {
  20. delete(puppet.bridge.puppetsByCustomMXID, puppet.CustomMXID)
  21. }
  22. puppet.bridge.puppetsLock.Unlock()
  23. puppet.CustomMXID = ""
  24. puppet.AccessToken = ""
  25. puppet.customIntent = nil
  26. puppet.customUser = nil
  27. if save {
  28. puppet.Update()
  29. }
  30. }
  31. func (puppet *Puppet) StartCustomMXID(reloginOnFail bool) error {
  32. newIntent, newAccessToken, err := puppet.bridge.DoublePuppet.Setup(puppet.CustomMXID, puppet.AccessToken, reloginOnFail)
  33. if err != nil {
  34. puppet.ClearCustomMXID()
  35. return err
  36. }
  37. puppet.bridge.puppetsLock.Lock()
  38. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  39. puppet.bridge.puppetsLock.Unlock()
  40. if puppet.AccessToken != newAccessToken {
  41. puppet.AccessToken = newAccessToken
  42. puppet.Update()
  43. }
  44. puppet.customIntent = newIntent
  45. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  46. return nil
  47. }
  48. func (user *User) tryAutomaticDoublePuppeting() {
  49. if !user.bridge.Config.CanAutoDoublePuppet(user.MXID) {
  50. return
  51. }
  52. user.log.Debug().Msg("Checking if double puppeting needs to be enabled")
  53. puppet := user.bridge.GetPuppetByID(user.DiscordID)
  54. if len(puppet.CustomMXID) > 0 {
  55. user.log.Debug().Msg("User already has double-puppeting enabled")
  56. // Custom puppet already enabled
  57. return
  58. }
  59. puppet.CustomMXID = user.MXID
  60. err := puppet.StartCustomMXID(true)
  61. if err != nil {
  62. user.log.Warn().Err(err).Msg("Failed to login with shared secret")
  63. } else {
  64. // TODO leave rooms with default puppet
  65. user.log.Debug().Msg("Successfully automatically enabled custom puppet")
  66. }
  67. }