puppet.go 9.7 KB

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