puppet.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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"
  10. "maunium.net/go/mautrix/appservice"
  11. "maunium.net/go/mautrix/bridge"
  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, puppet.IsWebhook)
  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 (br *DiscordBridge) reuploadUserAvatar(intent *appservice.IntentAPI, guildID, userID, avatarID string) (id.ContentURI, string, error) {
  174. var downloadURL, ext string
  175. if guildID == "" {
  176. downloadURL = discordgo.EndpointUserAvatar(userID, avatarID)
  177. ext = "png"
  178. if strings.HasPrefix(avatarID, "a_") {
  179. downloadURL = discordgo.EndpointUserAvatarAnimated(userID, avatarID)
  180. ext = "gif"
  181. }
  182. } else {
  183. downloadURL = discordgo.EndpointGuildMemberAvatar(guildID, userID, avatarID)
  184. ext = "png"
  185. if strings.HasPrefix(avatarID, "a_") {
  186. downloadURL = discordgo.EndpointGuildMemberAvatarAnimated(guildID, userID, avatarID)
  187. ext = "gif"
  188. }
  189. }
  190. if guildID == "" {
  191. url := br.Config.Bridge.MediaPatterns.Avatar(userID, avatarID, ext)
  192. if !url.IsEmpty() {
  193. return url, downloadURL, nil
  194. }
  195. }
  196. copied, err := br.copyAttachmentToMatrix(intent, downloadURL, false, AttachmentMeta{
  197. AttachmentID: fmt.Sprintf("avatar/%s/%s/%s", guildID, userID, avatarID),
  198. })
  199. if err != nil {
  200. return id.ContentURI{}, downloadURL, err
  201. }
  202. return copied.MXC, downloadURL, nil
  203. }
  204. func (puppet *Puppet) UpdateAvatar(info *discordgo.User) bool {
  205. avatarID := info.Avatar
  206. if puppet.IsWebhook && !puppet.bridge.Config.Bridge.EnableWebhookAvatars {
  207. avatarID = ""
  208. }
  209. if puppet.Avatar == avatarID && puppet.AvatarSet {
  210. return false
  211. }
  212. avatarChanged := avatarID != puppet.Avatar
  213. puppet.Avatar = avatarID
  214. puppet.AvatarSet = false
  215. puppet.AvatarURL = id.ContentURI{}
  216. if puppet.Avatar != "" && (puppet.AvatarURL.IsEmpty() || avatarChanged) {
  217. url, _, err := puppet.bridge.reuploadUserAvatar(puppet.DefaultIntent(), "", info.ID, puppet.Avatar)
  218. if err != nil {
  219. puppet.log.Warn().Err(err).Str("avatar_id", puppet.Avatar).Msg("Failed to reupload user avatar")
  220. return true
  221. }
  222. puppet.AvatarURL = url
  223. }
  224. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  225. if err != nil {
  226. puppet.log.Warn().Err(err).Msg("Failed to update avatar")
  227. } else {
  228. go puppet.updatePortalMeta(func(portal *Portal) {
  229. if portal.UpdateAvatarFromPuppet(puppet) {
  230. portal.Update()
  231. portal.UpdateBridgeInfo()
  232. }
  233. })
  234. puppet.AvatarSet = true
  235. }
  236. return true
  237. }
  238. func (puppet *Puppet) UpdateInfo(source *User, info *discordgo.User, webhookID string) {
  239. puppet.syncLock.Lock()
  240. defer puppet.syncLock.Unlock()
  241. if info == nil || len(info.Username) == 0 || len(info.Discriminator) == 0 {
  242. if puppet.Name != "" || source == nil {
  243. return
  244. }
  245. var err error
  246. puppet.log.Debug().Str("source_user", source.DiscordID).Msg("Fetching info through user to update puppet")
  247. info, err = source.Session.User(puppet.ID)
  248. if err != nil {
  249. puppet.log.Error().Err(err).Str("source_user", source.DiscordID).Msg("Failed to fetch info through user")
  250. return
  251. }
  252. }
  253. err := puppet.DefaultIntent().EnsureRegistered()
  254. if err != nil {
  255. puppet.log.Error().Err(err).Msg("Failed to ensure registered")
  256. }
  257. changed := false
  258. if webhookID != "" && webhookID == info.ID && !puppet.IsWebhook {
  259. puppet.IsWebhook = true
  260. changed = true
  261. }
  262. changed = puppet.UpdateContactInfo(info) || changed
  263. changed = puppet.UpdateName(info) || changed
  264. changed = puppet.UpdateAvatar(info) || changed
  265. if changed {
  266. puppet.Update()
  267. }
  268. }
  269. func (puppet *Puppet) UpdateContactInfo(info *discordgo.User) bool {
  270. changed := false
  271. if puppet.Username != info.Username {
  272. puppet.Username = info.Username
  273. changed = true
  274. }
  275. if puppet.GlobalName != info.GlobalName {
  276. puppet.GlobalName = info.GlobalName
  277. changed = true
  278. }
  279. if puppet.Discriminator != info.Discriminator {
  280. puppet.Discriminator = info.Discriminator
  281. changed = true
  282. }
  283. if puppet.IsBot != info.Bot {
  284. puppet.IsBot = info.Bot
  285. changed = true
  286. }
  287. if (changed && !puppet.IsWebhook) || !puppet.ContactInfoSet {
  288. puppet.ContactInfoSet = false
  289. puppet.ResendContactInfo()
  290. return true
  291. }
  292. return false
  293. }
  294. func (puppet *Puppet) ResendContactInfo() {
  295. if !puppet.bridge.SpecVersions.Supports(mautrix.BeeperFeatureArbitraryProfileMeta) || puppet.ContactInfoSet {
  296. return
  297. }
  298. contactInfo := map[string]any{
  299. "com.beeper.bridge.identifiers": []string{
  300. fmt.Sprintf("discord:%s#%s", puppet.Username, puppet.Discriminator),
  301. },
  302. "com.beeper.bridge.remote_id": puppet.ID,
  303. "com.beeper.bridge.service": puppet.bridge.BeeperServiceName,
  304. "com.beeper.bridge.network": puppet.bridge.BeeperNetworkName,
  305. "com.beeper.bridge.is_network_bot": puppet.IsBot,
  306. }
  307. if puppet.IsWebhook {
  308. contactInfo["com.beeper.bridge.identifiers"] = []string{}
  309. }
  310. err := puppet.DefaultIntent().BeeperUpdateProfile(contactInfo)
  311. if err != nil {
  312. puppet.log.Warn().Err(err).Msg("Failed to store custom contact info in profile")
  313. } else {
  314. puppet.ContactInfoSet = true
  315. }
  316. }