puppet.go 7.7 KB

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