puppet.go 7.8 KB

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