puppet.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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"
  25. "maunium.net/go/mautrix/appservice"
  26. "maunium.net/go/mautrix/bridge"
  27. "maunium.net/go/mautrix/id"
  28. "maunium.net/go/mautrix-whatsapp/config"
  29. "maunium.net/go/mautrix-whatsapp/database"
  30. )
  31. var userIDRegex *regexp.Regexp
  32. func (br *WABridge) ParsePuppetMXID(mxid id.UserID) (jid types.JID, ok bool) {
  33. if userIDRegex == nil {
  34. userIDRegex = br.Config.MakeUserIDRegex("([0-9]+)")
  35. }
  36. match := userIDRegex.FindStringSubmatch(string(mxid))
  37. if len(match) == 2 {
  38. jid = types.NewJID(match[1], types.DefaultUserServer)
  39. ok = true
  40. }
  41. return
  42. }
  43. func (br *WABridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
  44. jid, ok := br.ParsePuppetMXID(mxid)
  45. if !ok {
  46. return nil
  47. }
  48. return br.GetPuppetByJID(jid)
  49. }
  50. func (br *WABridge) GetPuppetByJID(jid types.JID) *Puppet {
  51. jid = jid.ToNonAD()
  52. if jid.Server == types.LegacyUserServer {
  53. jid.Server = types.DefaultUserServer
  54. } else if jid.Server != types.DefaultUserServer {
  55. return nil
  56. }
  57. br.puppetsLock.Lock()
  58. defer br.puppetsLock.Unlock()
  59. puppet, ok := br.puppets[jid]
  60. if !ok {
  61. dbPuppet := br.DB.Puppet.Get(jid)
  62. if dbPuppet == nil {
  63. dbPuppet = br.DB.Puppet.New()
  64. dbPuppet.JID = jid
  65. dbPuppet.Insert()
  66. }
  67. puppet = br.NewPuppet(dbPuppet)
  68. br.puppets[puppet.JID] = puppet
  69. if len(puppet.CustomMXID) > 0 {
  70. br.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  71. }
  72. }
  73. return puppet
  74. }
  75. func (br *WABridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
  76. br.puppetsLock.Lock()
  77. defer br.puppetsLock.Unlock()
  78. puppet, ok := br.puppetsByCustomMXID[mxid]
  79. if !ok {
  80. dbPuppet := br.DB.Puppet.GetByCustomMXID(mxid)
  81. if dbPuppet == nil {
  82. return nil
  83. }
  84. puppet = br.NewPuppet(dbPuppet)
  85. br.puppets[puppet.JID] = puppet
  86. br.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  87. }
  88. return puppet
  89. }
  90. func (user *User) GetIDoublePuppet() bridge.DoublePuppet {
  91. p := user.bridge.GetPuppetByCustomMXID(user.MXID)
  92. if p == nil || p.CustomIntent() == nil {
  93. return nil
  94. }
  95. return p
  96. }
  97. func (user *User) GetIGhost() bridge.Ghost {
  98. if user.JID.IsEmpty() {
  99. return nil
  100. }
  101. p := user.bridge.GetPuppetByJID(user.JID)
  102. if p == nil {
  103. return nil
  104. }
  105. return p
  106. }
  107. func (br *WABridge) IsGhost(id id.UserID) bool {
  108. _, ok := br.ParsePuppetMXID(id)
  109. return ok
  110. }
  111. func (br *WABridge) GetIGhost(id id.UserID) bridge.Ghost {
  112. p := br.GetPuppetByMXID(id)
  113. if p == nil {
  114. return nil
  115. }
  116. return p
  117. }
  118. func (puppet *Puppet) GetMXID() id.UserID {
  119. return puppet.MXID
  120. }
  121. func (br *WABridge) GetAllPuppetsWithCustomMXID() []*Puppet {
  122. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAllWithCustomMXID())
  123. }
  124. func (br *WABridge) GetAllPuppets() []*Puppet {
  125. return br.dbPuppetsToPuppets(br.DB.Puppet.GetAll())
  126. }
  127. func (br *WABridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
  128. br.puppetsLock.Lock()
  129. defer br.puppetsLock.Unlock()
  130. output := make([]*Puppet, len(dbPuppets))
  131. for index, dbPuppet := range dbPuppets {
  132. if dbPuppet == nil {
  133. continue
  134. }
  135. puppet, ok := br.puppets[dbPuppet.JID]
  136. if !ok {
  137. puppet = br.NewPuppet(dbPuppet)
  138. br.puppets[dbPuppet.JID] = puppet
  139. if len(dbPuppet.CustomMXID) > 0 {
  140. br.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
  141. }
  142. }
  143. output[index] = puppet
  144. }
  145. return output
  146. }
  147. func (br *WABridge) FormatPuppetMXID(jid types.JID) id.UserID {
  148. return id.NewUserID(
  149. br.Config.Bridge.FormatUsername(jid.User),
  150. br.Config.Homeserver.Domain)
  151. }
  152. func (br *WABridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  153. return &Puppet{
  154. Puppet: dbPuppet,
  155. bridge: br,
  156. log: br.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.JID)),
  157. MXID: br.FormatPuppetMXID(dbPuppet.JID),
  158. }
  159. }
  160. type Puppet struct {
  161. *database.Puppet
  162. bridge *WABridge
  163. log log.Logger
  164. typingIn id.RoomID
  165. typingAt time.Time
  166. MXID id.UserID
  167. customIntent *appservice.IntentAPI
  168. customUser *User
  169. syncLock sync.Mutex
  170. }
  171. var _ bridge.GhostWithProfile = (*Puppet)(nil)
  172. func (puppet *Puppet) GetDisplayname() string {
  173. return puppet.Displayname
  174. }
  175. func (puppet *Puppet) GetAvatarURL() id.ContentURI {
  176. return puppet.AvatarURL
  177. }
  178. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  179. if puppet.customIntent == nil || portal.Key.JID == puppet.JID || (portal.Key.JID.Server == types.BroadcastServer && portal.Key.Receiver != puppet.JID) {
  180. return puppet.DefaultIntent()
  181. }
  182. return puppet.customIntent
  183. }
  184. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  185. return puppet.customIntent
  186. }
  187. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  188. return puppet.bridge.AS.Intent(puppet.MXID)
  189. }
  190. func (puppet *Puppet) UpdateAvatar(source *User, forcePortalSync bool) bool {
  191. changed := source.updateAvatar(puppet.JID, false, &puppet.Avatar, &puppet.AvatarURL, &puppet.AvatarSet, puppet.log, puppet.DefaultIntent())
  192. if !changed || puppet.Avatar == "unauthorized" {
  193. if forcePortalSync {
  194. go puppet.updatePortalAvatar()
  195. }
  196. return changed
  197. }
  198. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  199. if err != nil {
  200. puppet.log.Warnln("Failed to set avatar:", err)
  201. } else {
  202. puppet.AvatarSet = true
  203. }
  204. go puppet.updatePortalAvatar()
  205. return true
  206. }
  207. func (puppet *Puppet) UpdateName(contact types.ContactInfo, forcePortalSync bool) bool {
  208. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(puppet.JID, contact)
  209. if (puppet.Displayname != newName || !puppet.NameSet) && quality >= puppet.NameQuality {
  210. oldName := puppet.Displayname
  211. puppet.Displayname = newName
  212. puppet.NameQuality = quality
  213. puppet.NameSet = false
  214. err := puppet.DefaultIntent().SetDisplayName(newName)
  215. if err == nil {
  216. puppet.log.Debugln("Updated name", oldName, "->", newName)
  217. puppet.NameSet = true
  218. go puppet.updatePortalName()
  219. } else {
  220. puppet.log.Warnln("Failed to set display name:", err)
  221. }
  222. return true
  223. } else if forcePortalSync {
  224. go puppet.updatePortalName()
  225. }
  226. return false
  227. }
  228. func (puppet *Puppet) UpdateContactInfo() bool {
  229. if !puppet.bridge.SpecVersions.Supports(mautrix.BeeperFeatureArbitraryProfileMeta) {
  230. return false
  231. }
  232. if puppet.ContactInfoSet {
  233. return false
  234. }
  235. contactInfo := map[string]any{
  236. "com.beeper.bridge.identifiers": []string{
  237. fmt.Sprintf("tel:+%s", puppet.JID.User),
  238. fmt.Sprintf("whatsapp:%s", puppet.JID.String()),
  239. },
  240. "com.beeper.bridge.remote_id": puppet.JID.String(),
  241. "com.beeper.bridge.service": "whatsapp",
  242. "com.beeper.bridge.network": "whatsapp",
  243. }
  244. err := puppet.DefaultIntent().BeeperUpdateProfile(contactInfo)
  245. if err != nil {
  246. puppet.log.Warnln("Failed to store custom contact info in profile:", err)
  247. return false
  248. } else {
  249. puppet.ContactInfoSet = true
  250. return true
  251. }
  252. }
  253. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  254. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  255. // Get room create lock to prevent races between receiving contact info and room creation.
  256. portal.roomCreateLock.Lock()
  257. meta(portal)
  258. portal.roomCreateLock.Unlock()
  259. }
  260. }
  261. func (puppet *Puppet) updatePortalAvatar() {
  262. puppet.updatePortalMeta(func(portal *Portal) {
  263. if portal.Avatar == puppet.Avatar && portal.AvatarURL == puppet.AvatarURL && (portal.AvatarSet || !portal.shouldSetDMRoomMetadata()) {
  264. return
  265. }
  266. portal.AvatarURL = puppet.AvatarURL
  267. portal.Avatar = puppet.Avatar
  268. portal.AvatarSet = false
  269. defer portal.Update(nil)
  270. if len(portal.MXID) > 0 && !portal.shouldSetDMRoomMetadata() {
  271. portal.UpdateBridgeInfo()
  272. } else if len(portal.MXID) > 0 {
  273. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  274. if err != nil {
  275. portal.log.Warnln("Failed to set avatar:", err)
  276. } else {
  277. portal.AvatarSet = true
  278. portal.UpdateBridgeInfo()
  279. }
  280. }
  281. })
  282. }
  283. func (puppet *Puppet) updatePortalName() {
  284. puppet.updatePortalMeta(func(portal *Portal) {
  285. portal.UpdateName(puppet.Displayname, types.EmptyJID, true)
  286. })
  287. }
  288. func (puppet *Puppet) SyncContact(source *User, onlyIfNoName, shouldHavePushName bool, reason string) {
  289. if onlyIfNoName && len(puppet.Displayname) > 0 && (!shouldHavePushName || puppet.NameQuality > config.NameQualityPhone) {
  290. source.EnqueuePuppetResync(puppet)
  291. return
  292. }
  293. contact, err := source.Client.Store.Contacts.GetContact(puppet.JID)
  294. if err != nil {
  295. puppet.log.Warnfln("Failed to get contact info through %s in SyncContact: %v (sync reason: %s)", source.MXID, reason)
  296. } else if !contact.Found {
  297. puppet.log.Warnfln("No contact info found through %s in SyncContact (sync reason: %s)", source.MXID, reason)
  298. }
  299. puppet.Sync(source, &contact, false, false)
  300. }
  301. func (puppet *Puppet) Sync(source *User, contact *types.ContactInfo, forceAvatarSync, forcePortalSync bool) {
  302. puppet.syncLock.Lock()
  303. defer puppet.syncLock.Unlock()
  304. err := puppet.DefaultIntent().EnsureRegistered()
  305. if err != nil {
  306. puppet.log.Errorln("Failed to ensure registered:", err)
  307. }
  308. puppet.log.Debugfln("Syncing info through %s", source.JID)
  309. update := false
  310. if contact != nil {
  311. if puppet.JID.User == source.JID.User {
  312. contact.PushName = source.Client.Store.PushName
  313. }
  314. update = puppet.UpdateName(*contact, forcePortalSync) || update
  315. }
  316. if len(puppet.Avatar) == 0 || forceAvatarSync || puppet.bridge.Config.Bridge.UserAvatarSync {
  317. update = puppet.UpdateAvatar(source, forcePortalSync) || update
  318. }
  319. update = puppet.UpdateContactInfo() || update
  320. if update || puppet.LastSync.Add(24*time.Hour).Before(time.Now()) {
  321. puppet.LastSync = time.Now()
  322. puppet.Update()
  323. }
  324. }