puppet.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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) ||
  145. // FIXME
  146. //(portal.backfilling && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling) ||
  147. portal.Key.JID == puppet.JID {
  148. return puppet.DefaultIntent()
  149. }
  150. return puppet.customIntent
  151. }
  152. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  153. return puppet.customIntent
  154. }
  155. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  156. return puppet.bridge.AS.Intent(puppet.MXID)
  157. }
  158. func reuploadAvatar(intent *appservice.IntentAPI, url string) (id.ContentURI, error) {
  159. getResp, err := http.DefaultClient.Get(url)
  160. if err != nil {
  161. return id.ContentURI{}, fmt.Errorf("failed to download avatar: %w", err)
  162. }
  163. data, err := io.ReadAll(getResp.Body)
  164. _ = getResp.Body.Close()
  165. if err != nil {
  166. return id.ContentURI{}, fmt.Errorf("failed to read avatar bytes: %w", err)
  167. }
  168. mime := http.DetectContentType(data)
  169. resp, err := intent.UploadBytes(data, mime)
  170. if err != nil {
  171. return id.ContentURI{}, fmt.Errorf("failed to upload avatar to Matrix: %w", err)
  172. }
  173. return resp.ContentURI, nil
  174. }
  175. func (puppet *Puppet) UpdateAvatar(source *User) bool {
  176. avatar, err := source.Client.GetProfilePictureInfo(puppet.JID, false)
  177. if err != nil {
  178. if !errors.Is(err, whatsmeow.ErrProfilePictureUnauthorized) {
  179. puppet.log.Warnln("Failed to get avatar URL:", err)
  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.Avatar = avatar.ID
  206. go puppet.updatePortalAvatar()
  207. return true
  208. }
  209. func (puppet *Puppet) UpdateName(source *User, contact types.ContactInfo) bool {
  210. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(puppet.JID, contact)
  211. if puppet.Displayname != newName && quality >= puppet.NameQuality {
  212. err := puppet.DefaultIntent().SetDisplayName(newName)
  213. if err == nil {
  214. puppet.Displayname = newName
  215. puppet.NameQuality = quality
  216. go puppet.updatePortalName()
  217. puppet.Update()
  218. } else {
  219. puppet.log.Warnln("Failed to set display name:", err)
  220. }
  221. return true
  222. }
  223. return false
  224. }
  225. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  226. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
  227. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  228. meta(portal)
  229. }
  230. }
  231. }
  232. func (puppet *Puppet) updatePortalAvatar() {
  233. puppet.updatePortalMeta(func(portal *Portal) {
  234. if len(portal.MXID) > 0 {
  235. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  236. if err != nil {
  237. portal.log.Warnln("Failed to set avatar:", err)
  238. }
  239. }
  240. portal.AvatarURL = puppet.AvatarURL
  241. portal.Avatar = puppet.Avatar
  242. portal.Update()
  243. })
  244. }
  245. func (puppet *Puppet) updatePortalName() {
  246. puppet.updatePortalMeta(func(portal *Portal) {
  247. if len(portal.MXID) > 0 {
  248. _, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
  249. if err != nil {
  250. portal.log.Warnln("Failed to set name:", err)
  251. }
  252. }
  253. portal.Name = puppet.Displayname
  254. portal.Update()
  255. })
  256. }
  257. func (puppet *Puppet) SyncContact(source *User, onlyIfNoName bool) {
  258. if onlyIfNoName && len(puppet.Displayname) > 0 {
  259. return
  260. }
  261. contact, err := source.Client.Store.Contacts.GetContact(puppet.JID)
  262. if err != nil {
  263. puppet.log.Warnfln("Failed to get contact info through %s in SyncContact: %v", source.MXID)
  264. } else if !contact.Found {
  265. puppet.log.Warnfln("No contact info found through %s in SyncContact", source.MXID)
  266. }
  267. puppet.Sync(source, contact)
  268. }
  269. func (puppet *Puppet) Sync(source *User, contact types.ContactInfo) {
  270. puppet.syncLock.Lock()
  271. defer puppet.syncLock.Unlock()
  272. err := puppet.DefaultIntent().EnsureRegistered()
  273. if err != nil {
  274. puppet.log.Errorln("Failed to ensure registered:", err)
  275. }
  276. if puppet.JID.User == source.JID.User {
  277. contact.PushName = source.Client.Store.PushName
  278. }
  279. update := false
  280. update = puppet.UpdateName(source, contact) || update
  281. if len(puppet.Avatar) == 0 || puppet.bridge.Config.Bridge.UserAvatarSync {
  282. update = puppet.UpdateAvatar(source) || update
  283. }
  284. if update {
  285. puppet.Update()
  286. }
  287. }