puppet.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "fmt"
  19. "net/http"
  20. "regexp"
  21. "strings"
  22. "sync"
  23. "github.com/Rhymen/go-whatsapp"
  24. log "maunium.net/go/maulogger/v2"
  25. "maunium.net/go/mautrix/appservice"
  26. "maunium.net/go/mautrix/id"
  27. "maunium.net/go/mautrix-whatsapp/database"
  28. )
  29. var userIDRegex *regexp.Regexp
  30. func (bridge *Bridge) ParsePuppetMXID(mxid id.UserID) (whatsapp.JID, bool) {
  31. if userIDRegex == nil {
  32. userIDRegex = regexp.MustCompile(fmt.Sprintf("^@%s:%s$",
  33. bridge.Config.Bridge.FormatUsername("([0-9]+)"),
  34. bridge.Config.Homeserver.Domain))
  35. }
  36. match := userIDRegex.FindStringSubmatch(string(mxid))
  37. if match == nil || len(match) != 2 {
  38. return "", false
  39. }
  40. jid := whatsapp.JID(match[1] + whatsapp.NewUserSuffix)
  41. return jid, true
  42. }
  43. func (bridge *Bridge) GetPuppetByMXID(mxid id.UserID) *Puppet {
  44. jid, ok := bridge.ParsePuppetMXID(mxid)
  45. if !ok {
  46. return nil
  47. }
  48. return bridge.GetPuppetByJID(jid)
  49. }
  50. func (bridge *Bridge) GetPuppetByJID(jid whatsapp.JID) *Puppet {
  51. bridge.puppetsLock.Lock()
  52. defer bridge.puppetsLock.Unlock()
  53. puppet, ok := bridge.puppets[jid]
  54. if !ok {
  55. dbPuppet := bridge.DB.Puppet.Get(jid)
  56. if dbPuppet == nil {
  57. dbPuppet = bridge.DB.Puppet.New()
  58. dbPuppet.JID = jid
  59. dbPuppet.Insert()
  60. }
  61. puppet = bridge.NewPuppet(dbPuppet)
  62. bridge.puppets[puppet.JID] = puppet
  63. if len(puppet.CustomMXID) > 0 {
  64. bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  65. }
  66. }
  67. return puppet
  68. }
  69. func (bridge *Bridge) GetPuppetByCustomMXID(mxid id.UserID) *Puppet {
  70. bridge.puppetsLock.Lock()
  71. defer bridge.puppetsLock.Unlock()
  72. puppet, ok := bridge.puppetsByCustomMXID[mxid]
  73. if !ok {
  74. dbPuppet := bridge.DB.Puppet.GetByCustomMXID(mxid)
  75. if dbPuppet == nil {
  76. return nil
  77. }
  78. puppet = bridge.NewPuppet(dbPuppet)
  79. bridge.puppets[puppet.JID] = puppet
  80. bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  81. }
  82. return puppet
  83. }
  84. func (bridge *Bridge) GetAllPuppetsWithCustomMXID() []*Puppet {
  85. return bridge.dbPuppetsToPuppets(bridge.DB.Puppet.GetAllWithCustomMXID())
  86. }
  87. func (bridge *Bridge) GetAllPuppets() []*Puppet {
  88. return bridge.dbPuppetsToPuppets(bridge.DB.Puppet.GetAll())
  89. }
  90. func (bridge *Bridge) dbPuppetsToPuppets(dbPuppets []*database.Puppet) []*Puppet {
  91. bridge.puppetsLock.Lock()
  92. defer bridge.puppetsLock.Unlock()
  93. output := make([]*Puppet, len(dbPuppets))
  94. for index, dbPuppet := range dbPuppets {
  95. if dbPuppet == nil {
  96. continue
  97. }
  98. puppet, ok := bridge.puppets[dbPuppet.JID]
  99. if !ok {
  100. puppet = bridge.NewPuppet(dbPuppet)
  101. bridge.puppets[dbPuppet.JID] = puppet
  102. if len(dbPuppet.CustomMXID) > 0 {
  103. bridge.puppetsByCustomMXID[dbPuppet.CustomMXID] = puppet
  104. }
  105. }
  106. output[index] = puppet
  107. }
  108. return output
  109. }
  110. func (bridge *Bridge) FormatPuppetMXID(jid whatsapp.JID) id.UserID {
  111. return id.NewUserID(
  112. bridge.Config.Bridge.FormatUsername(
  113. strings.Replace(
  114. jid,
  115. whatsapp.NewUserSuffix, "", 1)),
  116. bridge.Config.Homeserver.Domain)
  117. }
  118. func (bridge *Bridge) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  119. return &Puppet{
  120. Puppet: dbPuppet,
  121. bridge: bridge,
  122. log: bridge.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.JID)),
  123. MXID: bridge.FormatPuppetMXID(dbPuppet.JID),
  124. }
  125. }
  126. type Puppet struct {
  127. *database.Puppet
  128. bridge *Bridge
  129. log log.Logger
  130. typingIn id.RoomID
  131. typingAt int64
  132. MXID id.UserID
  133. customIntent *appservice.IntentAPI
  134. customTypingIn map[id.RoomID]bool
  135. customUser *User
  136. syncLock sync.Mutex
  137. }
  138. func (puppet *Puppet) PhoneNumber() string {
  139. return strings.Replace(puppet.JID, whatsapp.NewUserSuffix, "", 1)
  140. }
  141. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  142. if (!portal.IsPrivateChat() && puppet.customIntent == nil) ||
  143. (portal.backfilling && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling) ||
  144. 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 (puppet *Puppet) UpdateAvatar(source *User, avatar *whatsapp.ProfilePicInfo) bool {
  156. if avatar == nil {
  157. var err error
  158. avatar, err = source.Conn.GetProfilePicThumb(puppet.JID)
  159. if err != nil {
  160. puppet.log.Warnln("Failed to get avatar:", err)
  161. return false
  162. }
  163. }
  164. if avatar.Status == 404 {
  165. avatar.Tag = "remove"
  166. avatar.Status = 0
  167. } else if avatar.Status == 401 && puppet.Avatar != "unauthorized" {
  168. puppet.Avatar = "unauthorized"
  169. return true
  170. }
  171. if avatar.Status != 0 || avatar.Tag == puppet.Avatar {
  172. return false
  173. }
  174. if avatar.Tag == "remove" || len(avatar.URL) == 0 {
  175. err := puppet.DefaultIntent().SetAvatarURL(id.ContentURI{})
  176. if err != nil {
  177. puppet.log.Warnln("Failed to remove avatar:", err)
  178. }
  179. puppet.AvatarURL = id.ContentURI{}
  180. puppet.Avatar = avatar.Tag
  181. go puppet.updatePortalAvatar()
  182. return true
  183. }
  184. data, err := avatar.DownloadBytes()
  185. if err != nil {
  186. puppet.log.Warnln("Failed to download avatar:", err)
  187. return false
  188. }
  189. mime := http.DetectContentType(data)
  190. resp, err := puppet.DefaultIntent().UploadBytes(data, mime)
  191. if err != nil {
  192. puppet.log.Warnln("Failed to upload avatar:", err)
  193. return false
  194. }
  195. puppet.AvatarURL = resp.ContentURI
  196. err = puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  197. if err != nil {
  198. puppet.log.Warnln("Failed to set avatar:", err)
  199. }
  200. puppet.Avatar = avatar.Tag
  201. go puppet.updatePortalAvatar()
  202. return true
  203. }
  204. func (puppet *Puppet) UpdateName(source *User, contact whatsapp.Contact) bool {
  205. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact)
  206. if puppet.Displayname != newName && quality >= puppet.NameQuality {
  207. err := puppet.DefaultIntent().SetDisplayName(newName)
  208. if err == nil {
  209. puppet.Displayname = newName
  210. puppet.NameQuality = quality
  211. go puppet.updatePortalName()
  212. puppet.Update()
  213. } else {
  214. puppet.log.Warnln("Failed to set display name:", err)
  215. }
  216. return true
  217. }
  218. return false
  219. }
  220. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  221. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
  222. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  223. meta(portal)
  224. }
  225. }
  226. }
  227. func (puppet *Puppet) updatePortalAvatar() {
  228. puppet.updatePortalMeta(func(portal *Portal) {
  229. if len(portal.MXID) > 0 {
  230. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  231. if err != nil {
  232. portal.log.Warnln("Failed to set avatar:", err)
  233. }
  234. }
  235. portal.AvatarURL = puppet.AvatarURL
  236. portal.Avatar = puppet.Avatar
  237. portal.Update()
  238. })
  239. }
  240. func (puppet *Puppet) updatePortalName() {
  241. puppet.updatePortalMeta(func(portal *Portal) {
  242. if len(portal.MXID) > 0 {
  243. _, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
  244. if err != nil {
  245. portal.log.Warnln("Failed to set name:", err)
  246. }
  247. }
  248. portal.Name = puppet.Displayname
  249. portal.Update()
  250. })
  251. }
  252. func (puppet *Puppet) SyncContactIfNecessary(source *User) {
  253. if len(puppet.Displayname) > 0 {
  254. return
  255. }
  256. contact, ok := source.Conn.Store.Contacts[puppet.JID]
  257. if !ok {
  258. return
  259. }
  260. puppet.log.Debugfln("Syncing contact info through %s / %s because puppet has no displayname", source.MXID, source.JID)
  261. puppet.Sync(source, contact)
  262. }
  263. func (puppet *Puppet) Sync(source *User, contact whatsapp.Contact) {
  264. puppet.syncLock.Lock()
  265. defer puppet.syncLock.Unlock()
  266. err := puppet.DefaultIntent().EnsureRegistered()
  267. if err != nil {
  268. puppet.log.Errorln("Failed to ensure registered:", err)
  269. }
  270. if contact.JID == source.JID {
  271. contact.Notify = source.pushName
  272. }
  273. update := false
  274. update = puppet.UpdateName(source, contact) || update
  275. // TODO figure out how to update avatars after being offline
  276. if len(puppet.Avatar) == 0 || puppet.bridge.Config.Bridge.UserAvatarSync {
  277. update = puppet.UpdateAvatar(source, nil) || update
  278. }
  279. if update {
  280. puppet.Update()
  281. }
  282. }