puppet.go 8.6 KB

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