custompuppet.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2019 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. "encoding/json"
  22. "fmt"
  23. "strings"
  24. "time"
  25. "github.com/pkg/errors"
  26. "github.com/Rhymen/go-whatsapp"
  27. "maunium.net/go/mautrix"
  28. "maunium.net/go/mautrix-appservice"
  29. )
  30. var (
  31. ErrNoCustomMXID = errors.New("no custom mxid set")
  32. ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
  33. )
  34. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid string) error {
  35. prevCustomMXID := puppet.CustomMXID
  36. if puppet.customIntent != nil {
  37. puppet.stopSyncing()
  38. }
  39. puppet.CustomMXID = mxid
  40. puppet.AccessToken = accessToken
  41. err := puppet.StartCustomMXID()
  42. if err != nil {
  43. return err
  44. }
  45. if len(prevCustomMXID) > 0 {
  46. delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
  47. }
  48. if len(puppet.CustomMXID) > 0 {
  49. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  50. }
  51. puppet.Update()
  52. // TODO leave rooms with default puppet
  53. return nil
  54. }
  55. func (puppet *Puppet) loginWithSharedSecret(mxid string) (string, error) {
  56. mac := hmac.New(sha512.New, []byte(puppet.bridge.Config.Bridge.LoginSharedSecret))
  57. mac.Write([]byte(mxid))
  58. resp, err := puppet.bridge.AS.BotClient().Login(&mautrix.ReqLogin{
  59. Type: "m.login.password",
  60. Identifier: mautrix.UserIdentifier{Type: "m.id.user", User: mxid},
  61. Password: hex.EncodeToString(mac.Sum(nil)),
  62. DeviceID: "WhatsApp Bridge",
  63. InitialDeviceDisplayName: "WhatsApp Bridge",
  64. })
  65. if err != nil {
  66. return "", err
  67. }
  68. return resp.AccessToken, nil
  69. }
  70. func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
  71. if len(puppet.CustomMXID) == 0 {
  72. return nil, ErrNoCustomMXID
  73. }
  74. client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
  75. if err != nil {
  76. return nil, err
  77. }
  78. client.Logger = puppet.bridge.AS.Log.Sub(puppet.CustomMXID)
  79. client.Syncer = puppet
  80. client.Store = puppet
  81. ia := puppet.bridge.AS.NewIntentAPI("custom")
  82. ia.Client = client
  83. ia.Localpart = puppet.CustomMXID[1:strings.IndexRune(puppet.CustomMXID, ':')]
  84. ia.UserID = puppet.CustomMXID
  85. ia.IsCustomPuppet = true
  86. return ia, nil
  87. }
  88. func (puppet *Puppet) clearCustomMXID() {
  89. puppet.CustomMXID = ""
  90. puppet.AccessToken = ""
  91. puppet.customIntent = nil
  92. puppet.customTypingIn = nil
  93. puppet.customUser = nil
  94. }
  95. func (puppet *Puppet) StartCustomMXID() error {
  96. if len(puppet.CustomMXID) == 0 {
  97. puppet.clearCustomMXID()
  98. return nil
  99. }
  100. intent, err := puppet.newCustomIntent()
  101. if err != nil {
  102. puppet.clearCustomMXID()
  103. return err
  104. }
  105. urlPath := intent.BuildURL("account", "whoami")
  106. var resp struct{ UserID string `json:"user_id"` }
  107. _, err = intent.MakeRequest("GET", urlPath, nil, &resp)
  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[string]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, since 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 _, event := range events.Ephemeral.Events {
  152. switch event.Type {
  153. case mautrix.EphemeralEventReceipt:
  154. go puppet.handleReceiptEvent(portal, event)
  155. case mautrix.EphemeralEventTyping:
  156. go puppet.handleTypingEvent(portal, event)
  157. }
  158. }
  159. }
  160. for _, event := range resp.Presence.Events {
  161. if event.Sender != puppet.CustomMXID {
  162. continue
  163. }
  164. go puppet.handlePresenceEvent(event)
  165. }
  166. return nil
  167. }
  168. func (puppet *Puppet) handlePresenceEvent(event *mautrix.Event) {
  169. presence := whatsapp.PresenceAvailable
  170. if event.Content.Raw["presence"].(string) != "online" {
  171. presence = whatsapp.PresenceUnavailable
  172. puppet.customUser.log.Infoln("Marking offline")
  173. } else {
  174. puppet.customUser.log.Infoln("Marking online")
  175. }
  176. _, err := puppet.customUser.Conn.Presence("", presence)
  177. if err != nil {
  178. puppet.customUser.log.Warnln("Failed to set presence:", err)
  179. }
  180. }
  181. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *mautrix.Event) {
  182. for eventID, rawReceipts := range event.Content.Raw {
  183. if receipts, ok := rawReceipts.(map[string]interface{}); !ok {
  184. continue
  185. } else if readReceipt, ok := receipts["m.read"].(map[string]interface{}); !ok {
  186. continue
  187. } else if _, ok = readReceipt[puppet.CustomMXID].(map[string]interface{}); !ok {
  188. continue
  189. }
  190. message := puppet.bridge.DB.Message.GetByMXID(eventID)
  191. if message == nil {
  192. continue
  193. }
  194. puppet.customUser.log.Infofln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  195. _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
  196. if err != nil {
  197. puppet.customUser.log.Warnln("Error marking read:", err)
  198. }
  199. }
  200. }
  201. func (puppet *Puppet) handleTypingEvent(portal *Portal, event *mautrix.Event) {
  202. isTyping := false
  203. for _, userID := range event.Content.TypingUserIDs {
  204. if userID == puppet.CustomMXID {
  205. isTyping = true
  206. break
  207. }
  208. }
  209. if puppet.customTypingIn[event.RoomID] != isTyping {
  210. puppet.customTypingIn[event.RoomID] = isTyping
  211. presence := whatsapp.PresenceComposing
  212. if !isTyping {
  213. puppet.customUser.log.Infofln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  214. presence = whatsapp.PresencePaused
  215. } else {
  216. puppet.customUser.log.Infofln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  217. }
  218. _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
  219. if err != nil {
  220. puppet.customUser.log.Warnln("Error setting typing:", err)
  221. }
  222. }
  223. }
  224. func (puppet *Puppet) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
  225. puppet.log.Warnln("Sync error:", err)
  226. return 10 * time.Second, nil
  227. }
  228. func (puppet *Puppet) GetFilterJSON(_ string) json.RawMessage {
  229. mxid, _ := json.Marshal(puppet.CustomMXID)
  230. return json.RawMessage(fmt.Sprintf(`{
  231. "account_data": { "types": [] },
  232. "presence": {
  233. "senders": [
  234. %s
  235. ],
  236. "types": [
  237. "m.presence"
  238. ]
  239. },
  240. "room": {
  241. "ephemeral": {
  242. "types": [
  243. "m.typing",
  244. "m.receipt"
  245. ]
  246. },
  247. "include_leave": false,
  248. "account_data": { "types": [] },
  249. "state": { "types": [] },
  250. "timeline": { "types": [] }
  251. }
  252. }`, mxid))
  253. }
  254. func (puppet *Puppet) SaveFilterID(_, _ string) {}
  255. func (puppet *Puppet) SaveNextBatch(_, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  256. func (puppet *Puppet) SaveRoom(room *mautrix.Room) {}
  257. func (puppet *Puppet) LoadFilterID(_ string) string { return "" }
  258. func (puppet *Puppet) LoadNextBatch(_ string) string { return puppet.NextBatch }
  259. func (puppet *Puppet) LoadRoom(roomID string) *mautrix.Room { return nil }