custompuppet.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "crypto/hmac"
  19. "crypto/sha512"
  20. "encoding/hex"
  21. "errors"
  22. "time"
  23. "go.mau.fi/whatsmeow/types"
  24. "maunium.net/go/mautrix"
  25. "maunium.net/go/mautrix/appservice"
  26. "maunium.net/go/mautrix/event"
  27. "maunium.net/go/mautrix/id"
  28. )
  29. var (
  30. ErrNoCustomMXID = errors.New("no custom mxid set")
  31. ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
  32. )
  33. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid id.UserID) error {
  34. prevCustomMXID := puppet.CustomMXID
  35. if puppet.customIntent != nil {
  36. puppet.stopSyncing()
  37. }
  38. puppet.CustomMXID = mxid
  39. puppet.AccessToken = accessToken
  40. err := puppet.StartCustomMXID(false)
  41. if err != nil {
  42. return err
  43. }
  44. if len(prevCustomMXID) > 0 {
  45. delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
  46. }
  47. if len(puppet.CustomMXID) > 0 {
  48. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  49. }
  50. puppet.EnablePresence = puppet.bridge.Config.Bridge.DefaultBridgePresence
  51. puppet.EnableReceipts = puppet.bridge.Config.Bridge.DefaultBridgeReceipts
  52. puppet.bridge.AS.StateStore.MarkRegistered(puppet.CustomMXID)
  53. puppet.Update()
  54. // TODO leave rooms with default puppet
  55. return nil
  56. }
  57. func (puppet *Puppet) loginWithSharedSecret(mxid id.UserID) (string, error) {
  58. puppet.log.Debugfln("Logging into %s with shared secret", mxid)
  59. mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret))
  60. mac.Write([]byte(mxid))
  61. resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{
  62. Type: mautrix.AuthTypePassword,
  63. Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: string(mxid)},
  64. Password: hex.EncodeToString(mac.Sum(nil)),
  65. DeviceID: "WhatsApp Bridge",
  66. InitialDeviceDisplayName: "WhatsApp Bridge",
  67. })
  68. if err != nil {
  69. return "", err
  70. }
  71. return resp.AccessToken, nil
  72. }
  73. func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
  74. if len(puppet.CustomMXID) == 0 {
  75. return nil, ErrNoCustomMXID
  76. }
  77. client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
  78. if err != nil {
  79. return nil, err
  80. }
  81. client.Logger = puppet.bridge.AS.Log.Sub(string(puppet.CustomMXID))
  82. client.Client = puppet.bridge.AS.HTTPClient
  83. client.DefaultHTTPRetries = puppet.bridge.AS.DefaultHTTPRetries
  84. client.Syncer = puppet
  85. client.Store = puppet
  86. ia := puppet.bridge.AS.NewIntentAPI("custom")
  87. ia.Client = client
  88. ia.Localpart, _, _ = puppet.CustomMXID.Parse()
  89. ia.UserID = puppet.CustomMXID
  90. ia.IsCustomPuppet = true
  91. return ia, nil
  92. }
  93. func (puppet *Puppet) clearCustomMXID() {
  94. puppet.CustomMXID = ""
  95. puppet.AccessToken = ""
  96. puppet.customIntent = nil
  97. puppet.customTypingIn = nil
  98. puppet.customUser = nil
  99. }
  100. func (puppet *Puppet) StartCustomMXID(reloginOnFail bool) error {
  101. if len(puppet.CustomMXID) == 0 {
  102. puppet.clearCustomMXID()
  103. return nil
  104. }
  105. intent, err := puppet.newCustomIntent()
  106. if err != nil {
  107. puppet.clearCustomMXID()
  108. return err
  109. }
  110. resp, err := intent.Whoami()
  111. if err != nil {
  112. if !reloginOnFail || (errors.Is(err, mautrix.MUnknownToken) && !puppet.tryRelogin(err, "initializing double puppeting")) {
  113. puppet.clearCustomMXID()
  114. return err
  115. }
  116. intent.AccessToken = puppet.AccessToken
  117. } else if resp.UserID != puppet.CustomMXID {
  118. puppet.clearCustomMXID()
  119. return ErrMismatchingMXID
  120. }
  121. puppet.customIntent = intent
  122. puppet.customTypingIn = make(map[id.RoomID]bool)
  123. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  124. puppet.startSyncing()
  125. return nil
  126. }
  127. func (puppet *Puppet) startSyncing() {
  128. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  129. return
  130. }
  131. go func() {
  132. puppet.log.Debugln("Starting syncing...")
  133. puppet.customIntent.SyncPresence = "offline"
  134. err := puppet.customIntent.Sync()
  135. if err != nil {
  136. puppet.log.Errorln("Fatal error syncing:", err)
  137. }
  138. }()
  139. }
  140. func (puppet *Puppet) stopSyncing() {
  141. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  142. return
  143. }
  144. puppet.customIntent.StopSync()
  145. }
  146. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
  147. if !puppet.customUser.IsLoggedIn() {
  148. puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
  149. return nil
  150. }
  151. for roomID, events := range resp.Rooms.Join {
  152. portal := puppet.bridge.GetPortalByMXID(roomID)
  153. if portal == nil || portal.IsBroadcastList() {
  154. continue
  155. }
  156. for _, evt := range events.Ephemeral.Events {
  157. err := evt.Content.ParseRaw(evt.Type)
  158. if err != nil {
  159. continue
  160. }
  161. switch evt.Type {
  162. case event.EphemeralEventReceipt:
  163. if puppet.EnableReceipts {
  164. go puppet.handleReceiptEvent(portal, evt)
  165. }
  166. case event.EphemeralEventTyping:
  167. go puppet.handleTypingEvent(portal, evt)
  168. }
  169. }
  170. }
  171. if puppet.EnablePresence {
  172. for _, evt := range resp.Presence.Events {
  173. if evt.Sender != puppet.CustomMXID {
  174. continue
  175. }
  176. err := evt.Content.ParseRaw(evt.Type)
  177. if err != nil {
  178. continue
  179. }
  180. go puppet.handlePresenceEvent(evt)
  181. }
  182. }
  183. return nil
  184. }
  185. func (puppet *Puppet) handlePresenceEvent(event *event.Event) {
  186. presence := types.PresenceAvailable
  187. if event.Content.Raw["presence"].(string) != "online" {
  188. presence = types.PresenceUnavailable
  189. puppet.customUser.log.Debugln("Marking offline")
  190. } else {
  191. puppet.customUser.log.Debugln("Marking online")
  192. }
  193. err := puppet.customUser.Client.SendPresence(presence)
  194. if err != nil {
  195. puppet.customUser.log.Warnln("Failed to set presence:", err)
  196. }
  197. }
  198. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) {
  199. for eventID, receipts := range *event.Content.AsReceipt() {
  200. if receipt, ok := receipts.Read[puppet.CustomMXID]; !ok {
  201. // Ignore receipt events where this user isn't present.
  202. } else if isDoublePuppeted, _ := receipt.Extra["net.maunium.whatsapp.puppet"].(bool); isDoublePuppeted {
  203. puppet.customUser.log.Debugfln("Ignoring double puppeted read receipt %+v", event.Content.Raw)
  204. // Ignore double puppeted read receipts.
  205. } else if message := puppet.bridge.DB.Message.GetByMXID(eventID); message != nil {
  206. puppet.customUser.log.Debugfln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  207. err := puppet.customUser.Client.MarkRead([]types.MessageID{message.JID}, time.UnixMilli(receipt.Timestamp), portal.Key.JID, message.Sender)
  208. if err != nil {
  209. puppet.customUser.log.Warnln("Error marking read:", err)
  210. }
  211. }
  212. }
  213. }
  214. func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) {
  215. isTyping := false
  216. for _, userID := range evt.Content.AsTyping().UserIDs {
  217. if userID == puppet.CustomMXID {
  218. isTyping = true
  219. break
  220. }
  221. }
  222. if puppet.customTypingIn[evt.RoomID] != isTyping {
  223. puppet.customTypingIn[evt.RoomID] = isTyping
  224. presence := types.ChatPresenceComposing
  225. if !isTyping {
  226. puppet.customUser.log.Debugfln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  227. presence = types.ChatPresencePaused
  228. } else {
  229. puppet.customUser.log.Debugfln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  230. }
  231. err := puppet.customUser.Client.SendChatPresence(presence, portal.Key.JID)
  232. if err != nil {
  233. puppet.customUser.log.Warnln("Error setting typing:", err)
  234. }
  235. }
  236. }
  237. func (puppet *Puppet) tryRelogin(cause error, action string) bool {
  238. if !puppet.bridge.Config.CanDoublePuppet(puppet.CustomMXID) {
  239. return false
  240. }
  241. puppet.log.Debugfln("Trying to relogin after '%v' while %s", cause, action)
  242. accessToken, err := puppet.loginWithSharedSecret(puppet.CustomMXID)
  243. if err != nil {
  244. puppet.log.Errorfln("Failed to relogin after '%v' while %s: %v", cause, action, err)
  245. return false
  246. }
  247. puppet.log.Infofln("Successfully relogined after '%v' while %s", cause, action)
  248. puppet.AccessToken = accessToken
  249. return true
  250. }
  251. func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
  252. puppet.log.Warnln("Sync error:", err)
  253. if errors.Is(err, mautrix.MUnknownToken) {
  254. if !puppet.tryRelogin(err, "syncing") {
  255. return 0, err
  256. }
  257. puppet.customIntent.AccessToken = puppet.AccessToken
  258. return 0, nil
  259. }
  260. return 10 * time.Second, nil
  261. }
  262. func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
  263. everything := []event.Type{{Type: "*"}}
  264. return &mautrix.Filter{
  265. Presence: mautrix.FilterPart{
  266. Senders: []id.UserID{puppet.CustomMXID},
  267. Types: []event.Type{event.EphemeralEventPresence},
  268. },
  269. AccountData: mautrix.FilterPart{NotTypes: everything},
  270. Room: mautrix.RoomFilter{
  271. Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
  272. IncludeLeave: false,
  273. AccountData: mautrix.FilterPart{NotTypes: everything},
  274. State: mautrix.FilterPart{NotTypes: everything},
  275. Timeline: mautrix.FilterPart{NotTypes: everything},
  276. },
  277. }
  278. }
  279. func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
  280. func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  281. func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {}
  282. func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
  283. func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
  284. func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }