puppet.go 9.3 KB

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