puppet.go 7.6 KB

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