puppet.go 9.0 KB

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