custompuppet.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. "crypto/hmac"
  19. "crypto/sha512"
  20. "encoding/hex"
  21. "errors"
  22. "time"
  23. "github.com/Rhymen/go-whatsapp"
  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.Syncer = puppet
  83. client.Store = puppet
  84. ia := puppet.bridge.AS.NewIntentAPI("custom")
  85. ia.Client = client
  86. ia.Localpart, _, _ = puppet.CustomMXID.Parse()
  87. ia.UserID = puppet.CustomMXID
  88. ia.IsCustomPuppet = true
  89. return ia, nil
  90. }
  91. func (puppet *Puppet) clearCustomMXID() {
  92. puppet.CustomMXID = ""
  93. puppet.AccessToken = ""
  94. puppet.customIntent = nil
  95. puppet.customTypingIn = nil
  96. puppet.customUser = nil
  97. }
  98. func (puppet *Puppet) StartCustomMXID(reloginOnFail bool) error {
  99. if len(puppet.CustomMXID) == 0 {
  100. puppet.clearCustomMXID()
  101. return nil
  102. }
  103. intent, err := puppet.newCustomIntent()
  104. if err != nil {
  105. puppet.clearCustomMXID()
  106. return err
  107. }
  108. resp, err := intent.Whoami()
  109. if err != nil {
  110. if !reloginOnFail || (errors.Is(err, mautrix.MUnknownToken) && !puppet.tryRelogin(err, "initializing double puppeting")) {
  111. puppet.clearCustomMXID()
  112. return err
  113. }
  114. intent.AccessToken = puppet.AccessToken
  115. } else if resp.UserID != puppet.CustomMXID {
  116. puppet.clearCustomMXID()
  117. return ErrMismatchingMXID
  118. }
  119. puppet.customIntent = intent
  120. puppet.customTypingIn = make(map[id.RoomID]bool)
  121. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  122. puppet.startSyncing()
  123. return nil
  124. }
  125. func (puppet *Puppet) startSyncing() {
  126. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  127. return
  128. }
  129. go func() {
  130. puppet.log.Debugln("Starting syncing...")
  131. puppet.customIntent.SyncPresence = "offline"
  132. err := puppet.customIntent.Sync()
  133. if err != nil {
  134. puppet.log.Errorln("Fatal error syncing:", err)
  135. }
  136. }()
  137. }
  138. func (puppet *Puppet) stopSyncing() {
  139. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  140. return
  141. }
  142. puppet.customIntent.StopSync()
  143. }
  144. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
  145. if !puppet.customUser.IsConnected() {
  146. puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
  147. return nil
  148. }
  149. for roomID, events := range resp.Rooms.Join {
  150. portal := puppet.bridge.GetPortalByMXID(roomID)
  151. if portal == nil || portal.IsBroadcastList() {
  152. continue
  153. }
  154. for _, evt := range events.Ephemeral.Events {
  155. err := evt.Content.ParseRaw(evt.Type)
  156. if err != nil {
  157. continue
  158. }
  159. switch evt.Type {
  160. case event.EphemeralEventReceipt:
  161. if puppet.EnableReceipts {
  162. go puppet.handleReceiptEvent(portal, evt)
  163. }
  164. case event.EphemeralEventTyping:
  165. go puppet.handleTypingEvent(portal, evt)
  166. }
  167. }
  168. }
  169. if puppet.EnablePresence {
  170. for _, evt := range resp.Presence.Events {
  171. if evt.Sender != puppet.CustomMXID {
  172. continue
  173. }
  174. err := evt.Content.ParseRaw(evt.Type)
  175. if err != nil {
  176. continue
  177. }
  178. go puppet.handlePresenceEvent(evt)
  179. }
  180. }
  181. return nil
  182. }
  183. func (puppet *Puppet) handlePresenceEvent(event *event.Event) {
  184. presence := whatsapp.PresenceAvailable
  185. if event.Content.Raw["presence"].(string) != "online" {
  186. presence = whatsapp.PresenceUnavailable
  187. puppet.customUser.log.Debugln("Marking offline")
  188. } else {
  189. puppet.customUser.log.Debugln("Marking online")
  190. }
  191. _, err := puppet.customUser.Conn.Presence("", presence)
  192. if err != nil {
  193. puppet.customUser.log.Warnln("Failed to set presence:", err)
  194. }
  195. }
  196. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) {
  197. for eventID, receipts := range *event.Content.AsReceipt() {
  198. if _, ok := receipts.Read[puppet.CustomMXID]; !ok {
  199. continue
  200. }
  201. message := puppet.bridge.DB.Message.GetByMXID(eventID)
  202. if message == nil {
  203. continue
  204. }
  205. puppet.customUser.log.Debugfln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  206. _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
  207. if err != nil {
  208. puppet.customUser.log.Warnln("Error marking read:", err)
  209. }
  210. }
  211. }
  212. func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) {
  213. isTyping := false
  214. for _, userID := range evt.Content.AsTyping().UserIDs {
  215. if userID == puppet.CustomMXID {
  216. isTyping = true
  217. break
  218. }
  219. }
  220. if puppet.customTypingIn[evt.RoomID] != isTyping {
  221. puppet.customTypingIn[evt.RoomID] = isTyping
  222. presence := whatsapp.PresenceComposing
  223. if !isTyping {
  224. puppet.customUser.log.Debugfln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  225. presence = whatsapp.PresencePaused
  226. } else {
  227. puppet.customUser.log.Debugfln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  228. }
  229. _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
  230. if err != nil {
  231. puppet.customUser.log.Warnln("Error setting typing:", err)
  232. }
  233. }
  234. }
  235. func (puppet *Puppet) tryRelogin(cause error, action string) bool {
  236. if !puppet.bridge.Config.CanDoublePuppet(puppet.CustomMXID) {
  237. return false
  238. }
  239. puppet.log.Debugfln("Trying to relogin after '%v' while %s", cause, action)
  240. accessToken, err := puppet.loginWithSharedSecret(puppet.CustomMXID)
  241. if err != nil {
  242. puppet.log.Errorfln("Failed to relogin after '%v' while %s: %v", cause, action, err)
  243. return false
  244. }
  245. puppet.log.Infofln("Successfully relogined after '%v' while %s", cause, action)
  246. puppet.AccessToken = accessToken
  247. return true
  248. }
  249. func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
  250. puppet.log.Warnln("Sync error:", err)
  251. if errors.Is(err, mautrix.MUnknownToken) {
  252. if !puppet.tryRelogin(err, "syncing") {
  253. return 0, err
  254. }
  255. puppet.customIntent.AccessToken = puppet.AccessToken
  256. return 0, nil
  257. }
  258. return 10 * time.Second, nil
  259. }
  260. func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
  261. everything := []event.Type{{Type: "*"}}
  262. return &mautrix.Filter{
  263. Presence: mautrix.FilterPart{
  264. Senders: []id.UserID{puppet.CustomMXID},
  265. Types: []event.Type{event.EphemeralEventPresence},
  266. },
  267. AccountData: mautrix.FilterPart{NotTypes: everything},
  268. Room: mautrix.RoomFilter{
  269. Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
  270. IncludeLeave: false,
  271. AccountData: mautrix.FilterPart{NotTypes: everything},
  272. State: mautrix.FilterPart{NotTypes: everything},
  273. Timeline: mautrix.FilterPart{NotTypes: everything},
  274. },
  275. }
  276. }
  277. func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
  278. func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  279. func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {}
  280. func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
  281. func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
  282. func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }