puppet.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. "sync"
  6. "github.com/bwmarrin/discordgo"
  7. "github.com/rs/zerolog"
  8. "maunium.net/go/mautrix/appservice"
  9. "maunium.net/go/mautrix/bridge"
  10. "maunium.net/go/mautrix/bridge/bridgeconfig"
  11. "maunium.net/go/mautrix/id"
  12. "go.mau.fi/mautrix-discord/database"
  13. )
  14. type Puppet struct {
  15. *database.Puppet
  16. bridge *DiscordBridge
  17. log zerolog.Logger
  18. MXID id.UserID
  19. customIntent *appservice.IntentAPI
  20. customUser *User
  21. syncLock sync.Mutex
  22. }
  23. var _ bridge.Ghost = (*Puppet)(nil)
  24. var _ bridge.GhostWithProfile = (*Puppet)(nil)
  25. func (puppet *Puppet) GetMXID() id.UserID {
  26. return puppet.MXID
  27. }
  28. var userIDRegex *regexp.Regexp
  29. func (br *DiscordBridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  30. return &Puppet{
  31. Puppet: dbPuppet,
  32. bridge: br,
  33. log: br.ZLog.With().Str("discord_user_id", dbPuppet.ID).Logger(),
  34. MXID: br.FormatPuppetMXID(dbPuppet.ID),
  35. }
  36. }
  37. func (br *DiscordBridge) ParsePuppetMXID(mxid id.UserID) (string, bool) {
  38. if userIDRegex == nil {
  39. pattern := fmt.Sprintf(
  40. "^@%s:%s$",
  41. br.Config.Bridge.FormatUsername("([0-9]+)"),
  42. br.Config.Homeserver.Domain,
  43. )
  44. userIDRegex = regexp.MustCompile(pattern)
  45. }
  46. match := userIDRegex.FindStringSubmatch(string(mxid))
  47. if len(match) == 2 {
  48. return match[1], true
  49. }
  50. return "", false
  51. }
  52. func (br *DiscordBridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
  53. discordID, ok := br.ParsePuppetMXID(mxid)
  54. if !ok {
  55. return nil
  56. }
  57. return br.GetPuppetByID(discordID)
  58. }
  59. func (br *DiscordBridge) GetPuppetByID(id string) *Puppet {
  60. br.puppetsLock.Lock()
  61. defer br.puppetsLock.Unlock()
  62. puppet, ok := br.puppets[id]
  63. if !ok {
  64. dbPuppet := br.DB.Puppet.Get(id)
  65. if dbPuppet == nil {
  66. dbPuppet = br.DB.Puppet.New()
  67. dbPuppet.ID = id
  68. dbPuppet.Insert()
  69. }
  70. puppet = br.NewPuppet(dbPuppet)
  71. br.puppets[puppet.ID] = puppet
  72. }
  73. return puppet
  74. }
  75. func (br *DiscordBridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
  76. br.puppetsLock.Lock()
  77. defer br.puppetsLock.Unlock()
  78. puppet, ok := br.puppetsByCustomMXID[mxid]
  79. if !ok {
  80. dbPuppet := br.DB.Puppet.GetByCustomMXID(mxid)
  81. if dbPuppet == nil {
  82. return nil
  83. }
  84. puppet = br.NewPuppet(dbPuppet)
  85. br.puppets[puppet.ID] = puppet
  86. br.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  87. }
  88. return puppet
  89. }
  90. func (br *DiscordBridge) GetAllPuppetsWithCustomMXID() []*Puppet {
  91. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAllWithCustomMXID())
  92. }
  93. func (br *DiscordBridge) GetAllPuppets() []*Puppet {
  94. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAll())
  95. }
  96. func (br *DiscordBridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
  97. br.puppetsLock.Lock()
  98. defer br.puppetsLock.Unlock()
  99. output := make([]*Puppet, len(dbPuppets))
  100. for index, dbPuppet := range dbPuppets {
  101. if dbPuppet == nil {
  102. continue
  103. }
  104. puppet, ok := br.puppets[dbPuppet.ID]
  105. if !ok {
  106. puppet = br.NewPuppet(dbPuppet)
  107. br.puppets[dbPuppet.ID] = puppet
  108. if dbPuppet.CustomMXID != "" {
  109. br.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
  110. }
  111. }
  112. output[index] = puppet
  113. }
  114. return output
  115. }
  116. func (br *DiscordBridge) FormatPuppetMXID(did string) id.UserID {
  117. return id.NewUserID(
  118. br.Config.Bridge.FormatUsername(did),
  119. br.Config.Homeserver.Domain,
  120. )
  121. }
  122. func (puppet *Puppet) GetDisplayname() string {
  123. return puppet.Name
  124. }
  125. func (puppet *Puppet) GetAvatarURL() id.ContentURI {
  126. return puppet.AvatarURL
  127. }
  128. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  129. return puppet.bridge.AS.Intent(puppet.MXID)
  130. }
  131. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  132. if puppet.customIntent == nil || (portal.Key.Receiver != "" && portal.Key.Receiver != puppet.ID) {
  133. return puppet.DefaultIntent()
  134. }
  135. return puppet.customIntent
  136. }
  137. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  138. if puppet == nil {
  139. return nil
  140. }
  141. return puppet.customIntent
  142. }
  143. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  144. for _, portal := range puppet.bridge.GetDMPortalsWith(puppet.ID) {
  145. // Get room create lock to prevent races between receiving contact info and room creation.
  146. portal.roomCreateLock.Lock()
  147. meta(portal)
  148. portal.roomCreateLock.Unlock()
  149. }
  150. }
  151. func (puppet *Puppet) UpdateName(info *discordgo.User) bool {
  152. newName := puppet.bridge.Config.Bridge.FormatDisplayname(info)
  153. if puppet.Name == newName && puppet.NameSet {
  154. return false
  155. }
  156. puppet.Name = newName
  157. puppet.NameSet = false
  158. err := puppet.DefaultIntent().SetDisplayName(newName)
  159. if err != nil {
  160. puppet.log.Warn().Err(err).Msg("Failed to update displayname")
  161. } else {
  162. go puppet.updatePortalMeta(func(portal *Portal) {
  163. if portal.UpdateNameDirect(puppet.Name) {
  164. portal.Update()
  165. portal.UpdateBridgeInfo()
  166. }
  167. })
  168. puppet.NameSet = true
  169. }
  170. return true
  171. }
  172. func (puppet *Puppet) UpdateAvatar(info *discordgo.User) bool {
  173. if puppet.Avatar == info.Avatar && puppet.AvatarSet {
  174. return false
  175. }
  176. avatarChanged := info.Avatar != puppet.Avatar
  177. puppet.Avatar = info.Avatar
  178. puppet.AvatarSet = false
  179. puppet.AvatarURL = id.ContentURI{}
  180. // TODO should we just use discord's default avatars for users with no avatar?
  181. if puppet.Avatar != "" && (puppet.AvatarURL.IsEmpty() || avatarChanged) {
  182. url, err := uploadAvatar(puppet.DefaultIntent(), info.AvatarURL(""))
  183. if err != nil {
  184. puppet.log.Warn().Err(err).Str("avatar_id", puppet.Avatar).Msg("Failed to reupload user avatar")
  185. return true
  186. }
  187. puppet.AvatarURL = url
  188. }
  189. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  190. if err != nil {
  191. puppet.log.Warn().Err(err).Msg("Failed to update avatar")
  192. } else {
  193. go puppet.updatePortalMeta(func(portal *Portal) {
  194. if portal.UpdateAvatarFromPuppet(puppet) {
  195. portal.Update()
  196. portal.UpdateBridgeInfo()
  197. }
  198. })
  199. puppet.AvatarSet = true
  200. }
  201. return true
  202. }
  203. func (puppet *Puppet) UpdateInfo(source *User, info *discordgo.User) {
  204. puppet.syncLock.Lock()
  205. defer puppet.syncLock.Unlock()
  206. if info == nil || len(info.Username) == 0 || len(info.Discriminator) == 0 {
  207. if puppet.Name != "" || source == nil {
  208. return
  209. }
  210. var err error
  211. puppet.log.Debug().Str("source_user", source.DiscordID).Msg("Fetching info through user to update puppet")
  212. info, err = source.Session.User(puppet.ID)
  213. if err != nil {
  214. puppet.log.Error().Err(err).Str("source_user", source.DiscordID).Msg("Failed to fetch info through user")
  215. return
  216. }
  217. }
  218. err := puppet.DefaultIntent().EnsureRegistered()
  219. if err != nil {
  220. puppet.log.Error().Err(err).Msg("Failed to ensure registered")
  221. }
  222. changed := puppet.UpdateContactInfo(source, info)
  223. changed = puppet.UpdateName(info) || changed
  224. changed = puppet.UpdateAvatar(info) || changed
  225. if changed {
  226. puppet.Update()
  227. }
  228. }
  229. func (puppet *Puppet) UpdateContactInfo(source *User, info *discordgo.User) bool {
  230. if puppet.bridge.Config.Homeserver.Software != bridgeconfig.SoftwareHungry {
  231. return false
  232. }
  233. if puppet.ContactInfoSet {
  234. return false
  235. }
  236. contactInfo := map[string]any{
  237. "com.beeper.bridge.identifiers": []string{
  238. fmt.Sprintf("discord:%s#%s", info.Username, info.Discriminator),
  239. },
  240. "com.beeper.bridge.remote_id": puppet.ID,
  241. "com.beeper.bridge.service": puppet.bridge.BeeperServiceName,
  242. "com.beeper.bridge.network": puppet.bridge.BeeperNetworkName,
  243. "com.beeper.bridge.is_bridge_bot": false,
  244. "com.beeper.bridge.is_bot": info.Bot,
  245. }
  246. err := puppet.DefaultIntent().BeeperUpdateProfile(contactInfo)
  247. if err != nil {
  248. puppet.log.Warn().Err(err).Msg("Failed to store custom contact info in profile")
  249. return false
  250. } else {
  251. puppet.ContactInfoSet = true
  252. return true
  253. }
  254. }