custompuppet.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. "time"
  22. "github.com/pkg/errors"
  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()
  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. mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret))
  59. mac.Write([]byte(mxid))
  60. resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{
  61. Type: "m.login.password",
  62. Identifier: mautrix.UserIdentifier{Type: "m.id.user", User: string(mxid)},
  63. Password: hex.EncodeToString(mac.Sum(nil)),
  64. DeviceID: "WhatsApp Bridge",
  65. InitialDeviceDisplayName: "WhatsApp Bridge",
  66. })
  67. if err != nil {
  68. return "", err
  69. }
  70. return resp.AccessToken, nil
  71. }
  72. func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
  73. if len(puppet.CustomMXID) == 0 {
  74. return nil, ErrNoCustomMXID
  75. }
  76. client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
  77. if err != nil {
  78. return nil, err
  79. }
  80. client.Logger = puppet.bridge.AS.Log.Sub(string(puppet.CustomMXID))
  81. client.Syncer = puppet
  82. client.Store = puppet
  83. ia := puppet.bridge.AS.NewIntentAPI("custom")
  84. ia.Client = client
  85. ia.Localpart, _, _ = puppet.CustomMXID.Parse()
  86. ia.UserID = puppet.CustomMXID
  87. ia.IsCustomPuppet = true
  88. return ia, nil
  89. }
  90. func (puppet *Puppet) clearCustomMXID() {
  91. puppet.CustomMXID = ""
  92. puppet.AccessToken = ""
  93. puppet.customIntent = nil
  94. puppet.customTypingIn = nil
  95. puppet.customUser = nil
  96. }
  97. func (puppet *Puppet) StartCustomMXID() error {
  98. if len(puppet.CustomMXID) == 0 {
  99. puppet.clearCustomMXID()
  100. return nil
  101. }
  102. intent, err := puppet.newCustomIntent()
  103. if err != nil {
  104. puppet.clearCustomMXID()
  105. return err
  106. }
  107. resp, err := intent.Whoami()
  108. if err != nil {
  109. puppet.clearCustomMXID()
  110. return err
  111. }
  112. if resp.UserID != puppet.CustomMXID {
  113. puppet.clearCustomMXID()
  114. return ErrMismatchingMXID
  115. }
  116. puppet.customIntent = intent
  117. puppet.customTypingIn = make(map[id.RoomID]bool)
  118. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  119. puppet.startSyncing()
  120. return nil
  121. }
  122. func (puppet *Puppet) startSyncing() {
  123. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  124. return
  125. }
  126. go func() {
  127. puppet.log.Debugln("Starting syncing...")
  128. puppet.customIntent.SyncPresence = "offline"
  129. err := puppet.customIntent.Sync()
  130. if err != nil {
  131. puppet.log.Errorln("Fatal error syncing:", err)
  132. }
  133. }()
  134. }
  135. func (puppet *Puppet) stopSyncing() {
  136. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  137. return
  138. }
  139. puppet.customIntent.StopSync()
  140. }
  141. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, _ string) error {
  142. if !puppet.customUser.IsConnected() {
  143. puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
  144. return nil
  145. }
  146. for roomID, events := range resp.Rooms.Join {
  147. portal := puppet.bridge.GetPortalByMXID(roomID)
  148. if portal == nil {
  149. continue
  150. }
  151. for _, evt := range events.Ephemeral.Events {
  152. err := evt.Content.ParseRaw(evt.Type)
  153. if err != nil {
  154. continue
  155. }
  156. switch evt.Type {
  157. case event.EphemeralEventReceipt:
  158. if puppet.EnableReceipts {
  159. go puppet.handleReceiptEvent(portal, evt)
  160. }
  161. case event.EphemeralEventTyping:
  162. go puppet.handleTypingEvent(portal, evt)
  163. }
  164. }
  165. }
  166. if puppet.EnablePresence {
  167. for _, evt := range resp.Presence.Events {
  168. if evt.Sender != puppet.CustomMXID {
  169. continue
  170. }
  171. err := evt.Content.ParseRaw(evt.Type)
  172. if err != nil {
  173. continue
  174. }
  175. go puppet.handlePresenceEvent(evt)
  176. }
  177. }
  178. return nil
  179. }
  180. func (puppet *Puppet) handlePresenceEvent(event *event.Event) {
  181. presence := whatsapp.PresenceAvailable
  182. if event.Content.Raw["presence"].(string) != "online" {
  183. presence = whatsapp.PresenceUnavailable
  184. puppet.customUser.log.Debugln("Marking offline")
  185. } else {
  186. puppet.customUser.log.Debugln("Marking online")
  187. }
  188. _, err := puppet.customUser.Conn.Presence("", presence)
  189. if err != nil {
  190. puppet.customUser.log.Warnln("Failed to set presence:", err)
  191. }
  192. }
  193. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *event.Event) {
  194. for eventID, receipts := range *event.Content.AsReceipt() {
  195. if _, ok := receipts.Read[puppet.CustomMXID]; !ok {
  196. continue
  197. }
  198. message := puppet.bridge.DB.Message.GetByMXID(eventID)
  199. if message == nil {
  200. continue
  201. }
  202. puppet.customUser.log.Debugfln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  203. _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
  204. if err != nil {
  205. puppet.customUser.log.Warnln("Error marking read:", err)
  206. }
  207. }
  208. }
  209. func (puppet *Puppet) handleTypingEvent(portal *Portal, evt *event.Event) {
  210. isTyping := false
  211. for _, userID := range evt.Content.AsTyping().UserIDs {
  212. if userID == puppet.CustomMXID {
  213. isTyping = true
  214. break
  215. }
  216. }
  217. if puppet.customTypingIn[evt.RoomID] != isTyping {
  218. puppet.customTypingIn[evt.RoomID] = isTyping
  219. presence := whatsapp.PresenceComposing
  220. if !isTyping {
  221. puppet.customUser.log.Debugfln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  222. presence = whatsapp.PresencePaused
  223. } else {
  224. puppet.customUser.log.Debugfln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  225. }
  226. _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
  227. if err != nil {
  228. puppet.customUser.log.Warnln("Error setting typing:", err)
  229. }
  230. }
  231. }
  232. func (puppet *Puppet) OnFailedSync(_ *mautrix.RespSync, err error) (time.Duration, error) {
  233. puppet.log.Warnln("Sync error:", err)
  234. return 10 * time.Second, nil
  235. }
  236. func (puppet *Puppet) GetFilterJSON(_ id.UserID) *mautrix.Filter {
  237. everything := []event.Type{{Type: "*"}}
  238. return &mautrix.Filter{
  239. Presence: mautrix.FilterPart{
  240. Senders: []id.UserID{puppet.CustomMXID},
  241. Types: []event.Type{event.EphemeralEventPresence},
  242. },
  243. AccountData: mautrix.FilterPart{NotTypes: everything},
  244. Room: mautrix.RoomFilter{
  245. Ephemeral: mautrix.FilterPart{Types: []event.Type{event.EphemeralEventTyping, event.EphemeralEventReceipt}},
  246. IncludeLeave: false,
  247. AccountData: mautrix.FilterPart{NotTypes: everything},
  248. State: mautrix.FilterPart{NotTypes: everything},
  249. Timeline: mautrix.FilterPart{NotTypes: everything},
  250. },
  251. }
  252. }
  253. func (puppet *Puppet) SaveFilterID(_ id.UserID, _ string) {}
  254. func (puppet *Puppet) SaveNextBatch(_ id.UserID, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  255. func (puppet *Puppet) SaveRoom(_ *mautrix.Room) {}
  256. func (puppet *Puppet) LoadFilterID(_ id.UserID) string { return "" }
  257. func (puppet *Puppet) LoadNextBatch(_ id.UserID) string { return puppet.NextBatch }
  258. func (puppet *Puppet) LoadRoom(_ id.RoomID) *mautrix.Room { return nil }