puppet.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 (br *DiscordBridge) updatePuppetsContactInfo() {
  124. if br.Config.Homeserver.Software != bridgeconfig.SoftwareHungry {
  125. return
  126. }
  127. for _, puppet := range br.GetAllPuppets() {
  128. if !puppet.ContactInfoSet && puppet.NameSet {
  129. puppet.ResendContactInfo()
  130. puppet.Update()
  131. }
  132. }
  133. }
  134. func (puppet *Puppet) GetDisplayname() string {
  135. return puppet.Name
  136. }
  137. func (puppet *Puppet) GetAvatarURL() id.ContentURI {
  138. return puppet.AvatarURL
  139. }
  140. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  141. return puppet.bridge.AS.Intent(puppet.MXID)
  142. }
  143. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  144. if puppet.customIntent == nil || (portal.Key.Receiver != "" && portal.Key.Receiver != puppet.ID) {
  145. return puppet.DefaultIntent()
  146. }
  147. return puppet.customIntent
  148. }
  149. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  150. if puppet == nil {
  151. return nil
  152. }
  153. return puppet.customIntent
  154. }
  155. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  156. for _, portal := range puppet.bridge.GetDMPortalsWith(puppet.ID) {
  157. // Get room create lock to prevent races between receiving contact info and room creation.
  158. portal.roomCreateLock.Lock()
  159. meta(portal)
  160. portal.roomCreateLock.Unlock()
  161. }
  162. }
  163. func (puppet *Puppet) UpdateName(info *discordgo.User) bool {
  164. newName := puppet.bridge.Config.Bridge.FormatDisplayname(info)
  165. if puppet.Name == newName && puppet.NameSet {
  166. return false
  167. }
  168. puppet.Name = newName
  169. puppet.NameSet = false
  170. err := puppet.DefaultIntent().SetDisplayName(newName)
  171. if err != nil {
  172. puppet.log.Warn().Err(err).Msg("Failed to update displayname")
  173. } else {
  174. go puppet.updatePortalMeta(func(portal *Portal) {
  175. if portal.UpdateNameDirect(puppet.Name, false) {
  176. portal.Update()
  177. portal.UpdateBridgeInfo()
  178. }
  179. })
  180. puppet.NameSet = true
  181. }
  182. return true
  183. }
  184. func (puppet *Puppet) UpdateAvatar(info *discordgo.User) bool {
  185. if puppet.Avatar == info.Avatar && puppet.AvatarSet {
  186. return false
  187. }
  188. avatarChanged := info.Avatar != puppet.Avatar
  189. puppet.Avatar = info.Avatar
  190. puppet.AvatarSet = false
  191. puppet.AvatarURL = id.ContentURI{}
  192. if puppet.Avatar != "" && (puppet.AvatarURL.IsEmpty() || avatarChanged) {
  193. downloadURL := discordgo.EndpointUserAvatar(info.ID, info.Avatar)
  194. ext := "png"
  195. if strings.HasPrefix(info.Avatar, "a_") {
  196. downloadURL = discordgo.EndpointUserAvatarAnimated(info.ID, info.Avatar)
  197. ext = "gif"
  198. }
  199. url := puppet.bridge.Config.Bridge.MediaPatterns.Avatar(info.ID, info.Avatar, ext)
  200. if url.IsEmpty() {
  201. var err error
  202. url, err = uploadAvatar(puppet.DefaultIntent(), downloadURL)
  203. if err != nil {
  204. puppet.log.Warn().Err(err).Str("avatar_id", puppet.Avatar).Msg("Failed to reupload user avatar")
  205. return true
  206. }
  207. }
  208. puppet.AvatarURL = url
  209. }
  210. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  211. if err != nil {
  212. puppet.log.Warn().Err(err).Msg("Failed to update avatar")
  213. } else {
  214. go puppet.updatePortalMeta(func(portal *Portal) {
  215. if portal.UpdateAvatarFromPuppet(puppet) {
  216. portal.Update()
  217. portal.UpdateBridgeInfo()
  218. }
  219. })
  220. puppet.AvatarSet = true
  221. }
  222. return true
  223. }
  224. func (puppet *Puppet) UpdateInfo(source *User, info *discordgo.User) {
  225. puppet.syncLock.Lock()
  226. defer puppet.syncLock.Unlock()
  227. if info == nil || len(info.Username) == 0 || len(info.Discriminator) == 0 {
  228. if puppet.Name != "" || source == nil {
  229. return
  230. }
  231. var err error
  232. puppet.log.Debug().Str("source_user", source.DiscordID).Msg("Fetching info through user to update puppet")
  233. info, err = source.Session.User(puppet.ID)
  234. if err != nil {
  235. puppet.log.Error().Err(err).Str("source_user", source.DiscordID).Msg("Failed to fetch info through user")
  236. return
  237. }
  238. }
  239. err := puppet.DefaultIntent().EnsureRegistered()
  240. if err != nil {
  241. puppet.log.Error().Err(err).Msg("Failed to ensure registered")
  242. }
  243. changed := false
  244. changed = puppet.UpdateContactInfo(info) || changed
  245. changed = puppet.UpdateName(info) || changed
  246. changed = puppet.UpdateAvatar(info) || changed
  247. if changed {
  248. puppet.Update()
  249. }
  250. }
  251. func (puppet *Puppet) UpdateContactInfo(info *discordgo.User) bool {
  252. changed := false
  253. if puppet.Username != info.Username {
  254. puppet.Username = info.Username
  255. changed = true
  256. }
  257. if puppet.Discriminator != info.Discriminator {
  258. puppet.Discriminator = info.Discriminator
  259. changed = true
  260. }
  261. if puppet.IsBot != info.Bot {
  262. puppet.IsBot = info.Bot
  263. changed = true
  264. }
  265. if changed {
  266. puppet.ContactInfoSet = false
  267. puppet.ResendContactInfo()
  268. return true
  269. }
  270. return false
  271. }
  272. func (puppet *Puppet) ResendContactInfo() {
  273. if puppet.bridge.Config.Homeserver.Software != bridgeconfig.SoftwareHungry || puppet.ContactInfoSet {
  274. return
  275. }
  276. contactInfo := map[string]any{
  277. "com.beeper.bridge.identifiers": []string{
  278. fmt.Sprintf("discord:%s#%s", puppet.Username, puppet.Discriminator),
  279. },
  280. "com.beeper.bridge.remote_id": puppet.ID,
  281. "com.beeper.bridge.service": puppet.bridge.BeeperServiceName,
  282. "com.beeper.bridge.network": puppet.bridge.BeeperNetworkName,
  283. "com.beeper.bridge.is_network_bot": puppet.IsBot,
  284. }
  285. err := puppet.DefaultIntent().BeeperUpdateProfile(contactInfo)
  286. if err != nil {
  287. puppet.log.Warn().Err(err).Msg("Failed to store custom contact info in profile")
  288. } else {
  289. puppet.ContactInfoSet = true
  290. }
  291. }