puppet.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  175. if puppet.customIntent == nil || portal.Key.JID == puppet.JID || (portal.Key.JID.Server == types.BroadcastServer && portal.Key.Receiver != puppet.JID) {
  176. return puppet.DefaultIntent()
  177. }
  178. return puppet.customIntent
  179. }
  180. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  181. return puppet.customIntent
  182. }
  183. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  184. return puppet.bridge.AS.Intent(puppet.MXID)
  185. }
  186. func reuploadAvatar(intent *appservice.IntentAPI, url string) (id.ContentURI, error) {
  187. getResp, err := http.DefaultClient.Get(url)
  188. if err != nil {
  189. return id.ContentURI{}, fmt.Errorf("failed to download avatar: %w", err)
  190. }
  191. data, err := io.ReadAll(getResp.Body)
  192. _ = getResp.Body.Close()
  193. if err != nil {
  194. return id.ContentURI{}, fmt.Errorf("failed to read avatar bytes: %w", err)
  195. }
  196. mime := http.DetectContentType(data)
  197. resp, err := intent.UploadBytes(data, mime)
  198. if err != nil {
  199. return id.ContentURI{}, fmt.Errorf("failed to upload avatar to Matrix: %w", err)
  200. }
  201. return resp.ContentURI, nil
  202. }
  203. func (puppet *Puppet) UpdateAvatar(source *User) bool {
  204. oldAvatarID := puppet.Avatar
  205. changed := source.updateAvatar(puppet.JID, &puppet.Avatar, &puppet.AvatarURL, &puppet.AvatarSet, puppet.log, puppet.DefaultIntent())
  206. if !changed || puppet.Avatar == "unauthorized" {
  207. return changed
  208. }
  209. err := puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  210. if err != nil {
  211. puppet.log.Warnln("Failed to set avatar:", err)
  212. } else {
  213. puppet.log.Debugln("Updated avatar", oldAvatarID, "->", puppet.Avatar)
  214. puppet.AvatarSet = true
  215. }
  216. go puppet.updatePortalAvatar()
  217. return true
  218. }
  219. func (puppet *Puppet) UpdateName(contact types.ContactInfo) bool {
  220. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(puppet.JID, contact)
  221. if (puppet.Displayname != newName || !puppet.NameSet) && quality >= puppet.NameQuality {
  222. puppet.Displayname = newName
  223. puppet.NameQuality = quality
  224. puppet.NameSet = false
  225. err := puppet.DefaultIntent().SetDisplayName(newName)
  226. if err == nil {
  227. puppet.log.Debugln("Updated name", puppet.Displayname, "->", newName)
  228. puppet.NameSet = true
  229. go puppet.updatePortalName()
  230. } else {
  231. puppet.log.Warnln("Failed to set display name:", err)
  232. }
  233. return true
  234. }
  235. return false
  236. }
  237. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  238. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
  239. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  240. // Get room create lock to prevent races between receiving contact info and room creation.
  241. portal.roomCreateLock.Lock()
  242. meta(portal)
  243. portal.roomCreateLock.Unlock()
  244. }
  245. }
  246. }
  247. func (puppet *Puppet) updatePortalAvatar() {
  248. puppet.updatePortalMeta(func(portal *Portal) {
  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. }
  254. }
  255. portal.AvatarURL = puppet.AvatarURL
  256. portal.Avatar = puppet.Avatar
  257. portal.Update(nil)
  258. })
  259. }
  260. func (puppet *Puppet) updatePortalName() {
  261. puppet.updatePortalMeta(func(portal *Portal) {
  262. if len(portal.MXID) > 0 {
  263. _, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
  264. if err != nil {
  265. portal.log.Warnln("Failed to set name:", err)
  266. }
  267. }
  268. portal.Name = puppet.Displayname
  269. portal.Update(nil)
  270. })
  271. }
  272. func (puppet *Puppet) SyncContact(source *User, onlyIfNoName, shouldHavePushName bool, reason string) {
  273. if onlyIfNoName && len(puppet.Displayname) > 0 && (!shouldHavePushName || puppet.NameQuality > config.NameQualityPhone) {
  274. source.EnqueuePuppetResync(puppet)
  275. return
  276. }
  277. contact, err := source.Client.Store.Contacts.GetContact(puppet.JID)
  278. if err != nil {
  279. puppet.log.Warnfln("Failed to get contact info through %s in SyncContact: %v (sync reason: %s)", source.MXID, reason)
  280. } else if !contact.Found {
  281. puppet.log.Warnfln("No contact info found through %s in SyncContact (sync reason: %s)", source.MXID, reason)
  282. }
  283. puppet.Sync(source, &contact, false)
  284. }
  285. func (puppet *Puppet) Sync(source *User, contact *types.ContactInfo, forceAvatarSync bool) {
  286. puppet.syncLock.Lock()
  287. defer puppet.syncLock.Unlock()
  288. err := puppet.DefaultIntent().EnsureRegistered()
  289. if err != nil {
  290. puppet.log.Errorln("Failed to ensure registered:", err)
  291. }
  292. puppet.log.Debugfln("Syncing info through %s", source.JID)
  293. update := false
  294. if contact != nil {
  295. if puppet.JID.User == source.JID.User {
  296. contact.PushName = source.Client.Store.PushName
  297. }
  298. update = puppet.UpdateName(*contact) || update
  299. }
  300. if len(puppet.Avatar) == 0 || forceAvatarSync || puppet.bridge.Config.Bridge.UserAvatarSync {
  301. update = puppet.UpdateAvatar(source) || update
  302. }
  303. if update || puppet.LastSync.Add(24*time.Hour).Before(time.Now()) {
  304. puppet.LastSync = time.Now()
  305. puppet.Update()
  306. }
  307. }