puppet.go 9.5 KB

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