puppet.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. customTypingIn map[id.RoomID]bool
  141. customUser *User
  142. syncLock sync.Mutex
  143. }
  144. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  145. if (!portal.IsPrivateChat() && 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. }
  179. return false
  180. } else if avatar == nil {
  181. if puppet.Avatar == "remove" {
  182. return false
  183. }
  184. puppet.AvatarURL = id.ContentURI{}
  185. avatar = &types.ProfilePictureInfo{ID: "remove"}
  186. } else if avatar.ID == puppet.Avatar {
  187. return false
  188. } else if len(avatar.URL) == 0 {
  189. puppet.log.Warnln("Didn't get URL in response to avatar query")
  190. return false
  191. } else {
  192. url, err := reuploadAvatar(puppet.DefaultIntent(), avatar.URL)
  193. if err != nil {
  194. puppet.log.Warnln("Failed to reupload avatar:", err)
  195. return false
  196. }
  197. puppet.AvatarURL = url
  198. }
  199. err = puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  200. if err != nil {
  201. puppet.log.Warnln("Failed to set avatar:", err)
  202. }
  203. puppet.Avatar = avatar.ID
  204. go puppet.updatePortalAvatar()
  205. return true
  206. }
  207. func (puppet *Puppet) UpdateName(source *User, contact types.ContactInfo) bool {
  208. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(puppet.JID, contact)
  209. if puppet.Displayname != newName && quality >= puppet.NameQuality {
  210. err := puppet.DefaultIntent().SetDisplayName(newName)
  211. if err == nil {
  212. puppet.Displayname = newName
  213. puppet.NameQuality = quality
  214. go puppet.updatePortalName()
  215. puppet.Update()
  216. } else {
  217. puppet.log.Warnln("Failed to set display name:", err)
  218. }
  219. return true
  220. }
  221. return false
  222. }
  223. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  224. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
  225. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  226. meta(portal)
  227. }
  228. }
  229. }
  230. func (puppet *Puppet) updatePortalAvatar() {
  231. puppet.updatePortalMeta(func(portal *Portal) {
  232. if len(portal.MXID) > 0 {
  233. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  234. if err != nil {
  235. portal.log.Warnln("Failed to set avatar:", err)
  236. }
  237. }
  238. portal.AvatarURL = puppet.AvatarURL
  239. portal.Avatar = puppet.Avatar
  240. portal.Update()
  241. })
  242. }
  243. func (puppet *Puppet) updatePortalName() {
  244. puppet.updatePortalMeta(func(portal *Portal) {
  245. if len(portal.MXID) > 0 {
  246. _, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
  247. if err != nil {
  248. portal.log.Warnln("Failed to set name:", err)
  249. }
  250. }
  251. portal.Name = puppet.Displayname
  252. portal.Update()
  253. })
  254. }
  255. func (puppet *Puppet) SyncContact(source *User, onlyIfNoName bool) {
  256. if onlyIfNoName && len(puppet.Displayname) > 0 {
  257. return
  258. }
  259. contact, err := source.Client.Store.Contacts.GetContact(puppet.JID)
  260. if err != nil {
  261. puppet.log.Warnfln("Failed to get contact info through %s in SyncContact: %v", source.MXID)
  262. } else if !contact.Found {
  263. puppet.log.Warnfln("No contact info found through %s in SyncContact", source.MXID)
  264. }
  265. puppet.Sync(source, contact)
  266. }
  267. func (puppet *Puppet) Sync(source *User, contact types.ContactInfo) {
  268. puppet.syncLock.Lock()
  269. defer puppet.syncLock.Unlock()
  270. err := puppet.DefaultIntent().EnsureRegistered()
  271. if err != nil {
  272. puppet.log.Errorln("Failed to ensure registered:", err)
  273. }
  274. if puppet.JID.User == source.JID.User {
  275. contact.PushName = source.Client.Store.PushName
  276. }
  277. update := false
  278. update = puppet.UpdateName(source, contact) || update
  279. if len(puppet.Avatar) == 0 || puppet.bridge.Config.Bridge.UserAvatarSync {
  280. update = puppet.UpdateAvatar(source) || update
  281. }
  282. if update {
  283. puppet.Update()
  284. }
  285. }