puppet.go 8.0 KB

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