puppet.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "fmt"
  19. "regexp"
  20. "sync"
  21. "time"
  22. "go.mau.fi/whatsmeow/types"
  23. log "maunium.net/go/maulogger/v2"
  24. "maunium.net/go/mautrix/appservice"
  25. "maunium.net/go/mautrix/bridge"
  26. "maunium.net/go/mautrix/id"
  27. "maunium.net/go/mautrix-whatsapp/config"
  28. "maunium.net/go/mautrix-whatsapp/database"
  29. )
  30. var userIDRegex *regexp.Regexp
  31. func (br *WABridge) ParsePuppetMXID(mxid id.UserID) (jid types.JID, ok bool) {
  32. if userIDRegex == nil {
  33. userIDRegex = br.Config.MakeUserIDRegex("([0-9]+)")
  34. }
  35. match := userIDRegex.FindStringSubmatch(string(mxid))
  36. if len(match) == 2 {
  37. jid = types.NewJID(match[1], types.DefaultUserServer)
  38. ok = true
  39. }
  40. return
  41. }
  42. func (br *WABridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
  43. jid, ok := br.ParsePuppetMXID(mxid)
  44. if !ok {
  45. return nil
  46. }
  47. return br.GetPuppetByJID(jid)
  48. }
  49. func (br *WABridge) GetPuppetByJID(jid types.JID) *Puppet {
  50. jid = jid.ToNonAD()
  51. if jid.Server == types.LegacyUserServer {
  52. jid.Server = types.DefaultUserServer
  53. } else if jid.Server != types.DefaultUserServer {
  54. return nil
  55. }
  56. br.puppetsLock.Lock()
  57. defer br.puppetsLock.Unlock()
  58. puppet, ok := br.puppets[jid]
  59. if !ok {
  60. dbPuppet := br.DB.Puppet.Get(jid)
  61. if dbPuppet == nil {
  62. dbPuppet = br.DB.Puppet.New()
  63. dbPuppet.JID = jid
  64. dbPuppet.Insert()
  65. }
  66. puppet = br.NewPuppet(dbPuppet)
  67. br.puppets[puppet.JID] = puppet
  68. if len(puppet.CustomMXID) > 0 {
  69. br.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  70. }
  71. }
  72. return puppet
  73. }
  74. func (br *WABridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
  75. br.puppetsLock.Lock()
  76. defer br.puppetsLock.Unlock()
  77. puppet, ok := br.puppetsByCustomMXID[mxid]
  78. if !ok {
  79. dbPuppet := br.DB.Puppet.GetByCustomMXID(mxid)
  80. if dbPuppet == nil {
  81. return nil
  82. }
  83. puppet = br.NewPuppet(dbPuppet)
  84. br.puppets[puppet.JID] = puppet
  85. br.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  86. }
  87. return puppet
  88. }
  89. func (user *User) GetIDoublePuppet() bridge.DoublePuppet {
  90. p := user.bridge.GetPuppetByCustomMXID(user.MXID)
  91. if p == nil || p.CustomIntent() == nil {
  92. return nil
  93. }
  94. return p
  95. }
  96. func (user *User) GetIGhost() bridge.Ghost {
  97. if user.JID.IsEmpty() {
  98. return nil
  99. }
  100. p := user.bridge.GetPuppetByJID(user.JID)
  101. if p == nil {
  102. return nil
  103. }
  104. return p
  105. }
  106. func (br *WABridge) IsGhost(id id.UserID) bool {
  107. _, ok := br.ParsePuppetMXID(id)
  108. return ok
  109. }
  110. func (br *WABridge) GetIGhost(id id.UserID) bridge.Ghost {
  111. p := br.GetPuppetByMXID(id)
  112. if p == nil {
  113. return nil
  114. }
  115. return p
  116. }
  117. func (puppet *Puppet) GetMXID() id.UserID {
  118. return puppet.MXID
  119. }
  120. func (br *WABridge) GetAllPuppetsWithCustomMXID() []*Puppet {
  121. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAllWithCustomMXID())
  122. }
  123. func (br *WABridge) GetAllPuppets() []*Puppet {
  124. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAll())
  125. }
  126. func (br *WABridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
  127. br.puppetsLock.Lock()
  128. defer br.puppetsLock.Unlock()
  129. output := make([]*Puppet, len(dbPuppets))
  130. for index, dbPuppet := range dbPuppets {
  131. if dbPuppet == nil {
  132. continue
  133. }
  134. puppet, ok := br.puppets[dbPuppet.JID]
  135. if !ok {
  136. puppet = br.NewPuppet(dbPuppet)
  137. br.puppets[dbPuppet.JID] = puppet
  138. if len(dbPuppet.CustomMXID) > 0 {
  139. br.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
  140. }
  141. }
  142. output[index] = puppet
  143. }
  144. return output
  145. }
  146. func (br *WABridge) FormatPuppetMXID(jid types.JID) id.UserID {
  147. return id.NewUserID(
  148. br.Config.Bridge.FormatUsername(jid.User),
  149. br.Config.Homeserver.Domain)
  150. }
  151. func (br *WABridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  152. return &Puppet{
  153. Puppet: dbPuppet,
  154. bridge: br,
  155. log: br.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.JID)),
  156. MXID: br.FormatPuppetMXID(dbPuppet.JID),
  157. }
  158. }
  159. type Puppet struct {
  160. *database.Puppet
  161. bridge *WABridge
  162. log log.Logger
  163. typingIn id.RoomID
  164. typingAt time.Time
  165. MXID id.UserID
  166. customIntent *appservice.IntentAPI
  167. customUser *User
  168. syncLock sync.Mutex
  169. }
  170. var _ bridge.GhostWithProfile = (*Puppet)(nil)
  171. func (puppet *Puppet) GetDisplayname() string {
  172. return puppet.Displayname
  173. }
  174. func (puppet *Puppet) GetAvatarURL() id.ContentURI {
  175. return puppet.AvatarURL
  176. }
  177. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  178. if puppet.customIntent == nil || portal.Key.JID == puppet.JID || (portal.Key.JID.Server == types.BroadcastServer && portal.Key.Receiver != puppet.JID) {
  179. return puppet.DefaultIntent()
  180. }
  181. return puppet.customIntent
  182. }
  183. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  184. return puppet.customIntent
  185. }
  186. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  187. return puppet.bridge.AS.Intent(puppet.MXID)
  188. }
  189. func (puppet *Puppet) UpdateAvatar(source *User, forcePortalSync bool) bool {
  190. changed := source.updateAvatar(puppet.JID, false, &puppet.Avatar, &puppet.AvatarURL, &puppet.AvatarSet, puppet.log, puppet.DefaultIntent())
  191. if !changed || puppet.Avatar == "unauthorized" {
  192. if forcePortalSync {
  193. go puppet.updatePortalAvatar()
  194. }
  195. return changed
  196. }
  197. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  198. if err != nil {
  199. puppet.log.Warnln("Failed to set avatar:", err)
  200. } else {
  201. puppet.AvatarSet = true
  202. }
  203. go puppet.updatePortalAvatar()
  204. return true
  205. }
  206. func (puppet *Puppet) UpdateName(contact types.ContactInfo, forcePortalSync bool) bool {
  207. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(puppet.JID, contact)
  208. if (puppet.Displayname != newName || !puppet.NameSet) && quality >= puppet.NameQuality {
  209. oldName := puppet.Displayname
  210. puppet.Displayname = newName
  211. puppet.NameQuality = quality
  212. puppet.NameSet = false
  213. err := puppet.DefaultIntent().SetDisplayName(newName)
  214. if err == nil {
  215. puppet.log.Debugln("Updated name", oldName, "->", newName)
  216. puppet.NameSet = true
  217. go puppet.updatePortalName()
  218. } else {
  219. puppet.log.Warnln("Failed to set display name:", err)
  220. }
  221. return true
  222. } else if forcePortalSync {
  223. go puppet.updatePortalName()
  224. }
  225. return false
  226. }
  227. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  228. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta || puppet.bridge.Config.Bridge.Encryption.Allow {
  229. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  230. if !puppet.bridge.Config.Bridge.PrivateChatPortalMeta && !portal.Encrypted {
  231. continue
  232. }
  233. // Get room create lock to prevent races between receiving contact info and room creation.
  234. portal.roomCreateLock.Lock()
  235. meta(portal)
  236. portal.roomCreateLock.Unlock()
  237. }
  238. }
  239. }
  240. func (puppet *Puppet) updatePortalAvatar() {
  241. puppet.updatePortalMeta(func(portal *Portal) {
  242. if portal.Avatar == puppet.Avatar && portal.AvatarURL == puppet.AvatarURL && portal.AvatarSet {
  243. return
  244. }
  245. portal.AvatarURL = puppet.AvatarURL
  246. portal.Avatar = puppet.Avatar
  247. portal.AvatarSet = false
  248. defer portal.Update(nil)
  249. if len(portal.MXID) > 0 {
  250. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  251. if err != nil {
  252. portal.log.Warnln("Failed to set avatar:", err)
  253. } else {
  254. portal.AvatarSet = true
  255. portal.UpdateBridgeInfo()
  256. }
  257. }
  258. })
  259. }
  260. func (puppet *Puppet) updatePortalName() {
  261. puppet.updatePortalMeta(func(portal *Portal) {
  262. portal.UpdateName(puppet.Displayname, types.EmptyJID, true)
  263. })
  264. }
  265. func (puppet *Puppet) SyncContact(source *User, onlyIfNoName, shouldHavePushName bool, reason string) {
  266. if onlyIfNoName && len(puppet.Displayname) > 0 && (!shouldHavePushName || puppet.NameQuality > config.NameQualityPhone) {
  267. source.EnqueuePuppetResync(puppet)
  268. return
  269. }
  270. contact, err := source.Client.Store.Contacts.GetContact(puppet.JID)
  271. if err != nil {
  272. puppet.log.Warnfln("Failed to get contact info through %s in SyncContact: %v (sync reason: %s)", source.MXID, reason)
  273. } else if !contact.Found {
  274. puppet.log.Warnfln("No contact info found through %s in SyncContact (sync reason: %s)", source.MXID, reason)
  275. }
  276. puppet.Sync(source, &contact, false, false)
  277. }
  278. func (puppet *Puppet) Sync(source *User, contact *types.ContactInfo, forceAvatarSync, forcePortalSync bool) {
  279. puppet.syncLock.Lock()
  280. defer puppet.syncLock.Unlock()
  281. err := puppet.DefaultIntent().EnsureRegistered()
  282. if err != nil {
  283. puppet.log.Errorln("Failed to ensure registered:", err)
  284. }
  285. puppet.log.Debugfln("Syncing info through %s", source.JID)
  286. update := false
  287. if contact != nil {
  288. if puppet.JID.User == source.JID.User {
  289. contact.PushName = source.Client.Store.PushName
  290. }
  291. update = puppet.UpdateName(*contact, forcePortalSync) || update
  292. }
  293. if len(puppet.Avatar) == 0 || forceAvatarSync || puppet.bridge.Config.Bridge.UserAvatarSync {
  294. update = puppet.UpdateAvatar(source, forcePortalSync) || update
  295. }
  296. if update || puppet.LastSync.Add(24*time.Hour).Before(time.Now()) {
  297. puppet.LastSync = time.Now()
  298. puppet.Update()
  299. }
  300. }