puppet.go 9.6 KB

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