puppet.go 8.8 KB

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