puppet.go 9.2 KB

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