puppet.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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) NewPuppet(dbPuppet *database.Puppet) *Puppet {
  112. return &Puppet{
  113. Puppet: dbPuppet,
  114. bridge: bridge,
  115. log: bridge.Log.Sub(fmt.Sprintf("Puppet/%s", dbPuppet.JID)),
  116. MXID: id.NewUserID(
  117. bridge.Config.Bridge.FormatUsername(
  118. strings.Replace(
  119. dbPuppet.JID,
  120. whatsappExt.NewUserSuffix, "", 1)),
  121. bridge.Config.Homeserver.Domain),
  122. }
  123. }
  124. type Puppet struct {
  125. *database.Puppet
  126. bridge *Bridge
  127. log log.Logger
  128. typingIn id.RoomID
  129. typingAt int64
  130. MXID id.UserID
  131. customIntent *appservice.IntentAPI
  132. customTypingIn map[id.RoomID]bool
  133. customUser *User
  134. }
  135. func (puppet *Puppet) PhoneNumber() string {
  136. return strings.Replace(puppet.JID, whatsappExt.NewUserSuffix, "", 1)
  137. }
  138. func (puppet *Puppet) IntentFor(portal *Portal) *appservice.IntentAPI {
  139. if (!portal.IsPrivateChat() && puppet.customIntent == nil) ||
  140. (portal.backfilling && portal.bridge.Config.Bridge.InviteOwnPuppetForBackfilling) ||
  141. portal.Key.JID == puppet.JID {
  142. return puppet.DefaultIntent()
  143. }
  144. return puppet.customIntent
  145. }
  146. func (puppet *Puppet) CustomIntent() *appservice.IntentAPI {
  147. return puppet.customIntent
  148. }
  149. func (puppet *Puppet) DefaultIntent() *appservice.IntentAPI {
  150. return puppet.bridge.AS.Intent(puppet.MXID)
  151. }
  152. func (puppet *Puppet) UpdateAvatar(source *User, avatar *whatsappExt.ProfilePicInfo) bool {
  153. if avatar == nil {
  154. var err error
  155. avatar, err = source.Conn.GetProfilePicThumb(puppet.JID)
  156. if err != nil {
  157. puppet.log.Warnln("Failed to get avatar:", err)
  158. return false
  159. }
  160. }
  161. if avatar.Status != 0 {
  162. return false
  163. }
  164. if avatar.Tag == puppet.Avatar {
  165. return false
  166. }
  167. if len(avatar.URL) == 0 {
  168. err := puppet.DefaultIntent().SetAvatarURL(id.ContentURI{})
  169. if err != nil {
  170. puppet.log.Warnln("Failed to remove avatar:", err)
  171. }
  172. puppet.AvatarURL = id.ContentURI{}
  173. puppet.Avatar = avatar.Tag
  174. go puppet.updatePortalAvatar()
  175. return true
  176. }
  177. data, err := avatar.DownloadBytes()
  178. if err != nil {
  179. puppet.log.Warnln("Failed to download avatar:", err)
  180. return false
  181. }
  182. mime := http.DetectContentType(data)
  183. resp, err := puppet.DefaultIntent().UploadBytes(data, mime)
  184. if err != nil {
  185. puppet.log.Warnln("Failed to upload avatar:", err)
  186. return false
  187. }
  188. puppet.AvatarURL = resp.ContentURI
  189. err = puppet.DefaultIntent().SetAvatarURL(puppet.AvatarURL)
  190. if err != nil {
  191. puppet.log.Warnln("Failed to set avatar:", err)
  192. }
  193. puppet.Avatar = avatar.Tag
  194. go puppet.updatePortalAvatar()
  195. return true
  196. }
  197. func (puppet *Puppet) UpdateName(source *User, contact whatsapp.Contact) bool {
  198. newName, quality := puppet.bridge.Config.Bridge.FormatDisplayname(contact)
  199. if puppet.Displayname != newName && quality >= puppet.NameQuality {
  200. err := puppet.DefaultIntent().SetDisplayName(newName)
  201. if err == nil {
  202. puppet.Displayname = newName
  203. puppet.NameQuality = quality
  204. go puppet.updatePortalName()
  205. puppet.Update()
  206. } else {
  207. puppet.log.Warnln("Failed to set display name:", err)
  208. }
  209. return true
  210. }
  211. return false
  212. }
  213. func (puppet *Puppet) updatePortalMeta(meta func(portal *Portal)) {
  214. if puppet.bridge.Config.Bridge.PrivateChatPortalMeta {
  215. for _, portal := range puppet.bridge.GetAllPortalsByJID(puppet.JID) {
  216. meta(portal)
  217. }
  218. }
  219. }
  220. func (puppet *Puppet) updatePortalAvatar() {
  221. puppet.updatePortalMeta(func(portal *Portal) {
  222. if len(portal.MXID) > 0 {
  223. _, err := portal.MainIntent().SetRoomAvatar(portal.MXID, puppet.AvatarURL)
  224. if err != nil {
  225. portal.log.Warnln("Failed to set avatar:", err)
  226. }
  227. }
  228. portal.AvatarURL = puppet.AvatarURL
  229. portal.Avatar = puppet.Avatar
  230. portal.Update()
  231. })
  232. }
  233. func (puppet *Puppet) updatePortalName() {
  234. puppet.updatePortalMeta(func(portal *Portal) {
  235. if len(portal.MXID) > 0 {
  236. _, err := portal.MainIntent().SetRoomName(portal.MXID, puppet.Displayname)
  237. if err != nil {
  238. portal.log.Warnln("Failed to set name:", err)
  239. }
  240. }
  241. portal.Name = puppet.Displayname
  242. portal.Update()
  243. })
  244. }
  245. func (puppet *Puppet) Sync(source *User, contact whatsapp.Contact) {
  246. err := puppet.DefaultIntent().EnsureRegistered()
  247. if err != nil {
  248. puppet.log.Errorln("Failed to ensure registered:", err)
  249. }
  250. if contact.Jid == source.JID {
  251. contact.Notify = source.Conn.Info.Pushname
  252. }
  253. update := false
  254. update = puppet.UpdateName(source, contact) || update
  255. update = puppet.UpdateAvatar(source, nil) || update
  256. if update {
  257. puppet.Update()
  258. }
  259. }