custompuppet.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. "os"
  24. "strings"
  25. "time"
  26. "github.com/pkg/errors"
  27. "github.com/Rhymen/go-whatsapp"
  28. "maunium.net/go/mautrix"
  29. appservice "maunium.net/go/mautrix-appservice"
  30. )
  31. var (
  32. ErrNoCustomMXID = errors.New("no custom mxid set")
  33. ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
  34. )
  35. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid string) error {
  36. prevCustomMXID := puppet.CustomMXID
  37. if puppet.customIntent != nil {
  38. puppet.stopSyncing()
  39. }
  40. puppet.CustomMXID = mxid
  41. puppet.AccessToken = accessToken
  42. err := puppet.StartCustomMXID()
  43. if err != nil {
  44. return err
  45. }
  46. if len(prevCustomMXID) > 0 {
  47. delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
  48. }
  49. if len(puppet.CustomMXID) > 0 {
  50. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  51. }
  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 string) (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: 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(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[1:strings.IndexRune(puppet.CustomMXID, ':')]
  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. urlPath := intent.BuildURL("account", "whoami")
  108. var resp struct {
  109. UserID string `json:"user_id"`
  110. }
  111. _, err = intent.MakeRequest("GET", urlPath, nil, &resp)
  112. if err != nil {
  113. puppet.clearCustomMXID()
  114. return err
  115. }
  116. if resp.UserID != puppet.CustomMXID {
  117. puppet.clearCustomMXID()
  118. return ErrMismatchingMXID
  119. }
  120. puppet.customIntent = intent
  121. puppet.customTypingIn = make(map[string]bool)
  122. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  123. puppet.startSyncing()
  124. return nil
  125. }
  126. func (puppet *Puppet) startSyncing() {
  127. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  128. return
  129. }
  130. go func() {
  131. puppet.log.Debugln("Starting syncing...")
  132. puppet.customIntent.SyncPresence = "offline"
  133. err := puppet.customIntent.Sync()
  134. if err != nil {
  135. puppet.log.Errorln("Fatal error syncing:", err)
  136. }
  137. }()
  138. }
  139. func (puppet *Puppet) stopSyncing() {
  140. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  141. return
  142. }
  143. puppet.customIntent.StopSync()
  144. }
  145. func parseEvent(roomID string, data json.RawMessage) *mautrix.Event {
  146. event := &mautrix.Event{}
  147. err := json.Unmarshal(data, event)
  148. if err != nil {
  149. // TODO add separate handler for these
  150. _, _ = fmt.Fprintf(os.Stderr, "Failed to unmarshal event: %v\n%s\n", err, string(data))
  151. return nil
  152. }
  153. return event
  154. }
  155. func parsePresenceEvent(data json.RawMessage) *mautrix.Event {
  156. event := &mautrix.Event{}
  157. err := json.Unmarshal(data, event)
  158. if err != nil {
  159. // TODO add separate handler for these
  160. _, _ = fmt.Fprintf(os.Stderr, "Failed to unmarshal event: %v\n%s\n", err, string(data))
  161. return nil
  162. }
  163. return event
  164. }
  165. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, since string) error {
  166. if !puppet.customUser.IsConnected() {
  167. puppet.log.Debugln("Skipping sync processing: custom user not connected to whatsapp")
  168. return nil
  169. }
  170. for roomID, events := range resp.Rooms.Join {
  171. portal := puppet.bridge.GetPortalByMXID(roomID)
  172. if portal == nil {
  173. continue
  174. }
  175. for _, data := range events.Ephemeral.Events {
  176. event := parseEvent(roomID, data)
  177. if event != nil {
  178. switch event.Type {
  179. case mautrix.EphemeralEventReceipt:
  180. go puppet.handleReceiptEvent(portal, event)
  181. case mautrix.EphemeralEventTyping:
  182. go puppet.handleTypingEvent(portal, event)
  183. }
  184. }
  185. }
  186. }
  187. for _, data := range resp.Presence.Events {
  188. event := parsePresenceEvent(data)
  189. if event != nil {
  190. if event.Sender != puppet.CustomMXID {
  191. continue
  192. }
  193. go puppet.handlePresenceEvent(event)
  194. }
  195. }
  196. return nil
  197. }
  198. func (puppet *Puppet) handlePresenceEvent(event *mautrix.Event) {
  199. presence := whatsapp.PresenceAvailable
  200. if event.Content.Raw["presence"].(string) != "online" {
  201. presence = whatsapp.PresenceUnavailable
  202. puppet.customUser.log.Infoln("Marking offline")
  203. } else {
  204. puppet.customUser.log.Infoln("Marking online")
  205. }
  206. _, err := puppet.customUser.Conn.Presence("", presence)
  207. if err != nil {
  208. puppet.customUser.log.Warnln("Failed to set presence:", err)
  209. }
  210. }
  211. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *mautrix.Event) {
  212. for eventID, rawReceipts := range event.Content.Raw {
  213. if receipts, ok := rawReceipts.(map[string]interface{}); !ok {
  214. continue
  215. } else if readReceipt, ok := receipts["m.read"].(map[string]interface{}); !ok {
  216. continue
  217. } else if _, ok = readReceipt[puppet.CustomMXID].(map[string]interface{}); !ok {
  218. continue
  219. }
  220. message := puppet.bridge.DB.Message.GetByMXID(eventID)
  221. if message == nil {
  222. continue
  223. }
  224. puppet.customUser.log.Infofln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  225. _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
  226. if err != nil {
  227. puppet.customUser.log.Warnln("Error marking read:", err)
  228. }
  229. }
  230. }
  231. func (puppet *Puppet) handleTypingEvent(portal *Portal, event *mautrix.Event) {
  232. isTyping := false
  233. for _, userID := range event.Content.TypingUserIDs {
  234. if userID == puppet.CustomMXID {
  235. isTyping = true
  236. break
  237. }
  238. }
  239. if puppet.customTypingIn[event.RoomID] != isTyping {
  240. puppet.customTypingIn[event.RoomID] = isTyping
  241. presence := whatsapp.PresenceComposing
  242. if !isTyping {
  243. puppet.customUser.log.Infofln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  244. presence = whatsapp.PresencePaused
  245. } else {
  246. puppet.customUser.log.Infofln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  247. }
  248. _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
  249. if err != nil {
  250. puppet.customUser.log.Warnln("Error setting typing:", err)
  251. }
  252. }
  253. }
  254. func (puppet *Puppet) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
  255. puppet.log.Warnln("Sync error:", err)
  256. return 10 * time.Second, nil
  257. }
  258. func (puppet *Puppet) GetFilterJSON(_ string) json.RawMessage {
  259. mxid, _ := json.Marshal(puppet.CustomMXID)
  260. return json.RawMessage(fmt.Sprintf(`{
  261. "account_data": { "types": [] },
  262. "presence": {
  263. "senders": [
  264. %s
  265. ],
  266. "types": [
  267. "m.presence"
  268. ]
  269. },
  270. "room": {
  271. "ephemeral": {
  272. "types": [
  273. "m.typing",
  274. "m.receipt"
  275. ]
  276. },
  277. "include_leave": false,
  278. "account_data": { "types": [] },
  279. "state": { "types": [] },
  280. "timeline": { "types": [] }
  281. }
  282. }`, mxid))
  283. }
  284. func (puppet *Puppet) SaveFilterID(_, _ string) {}
  285. func (puppet *Puppet) SaveNextBatch(_, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  286. func (puppet *Puppet) SaveRoom(room *mautrix.Room) {}
  287. func (puppet *Puppet) LoadFilterID(_ string) string { return "" }
  288. func (puppet *Puppet) LoadNextBatch(_ string) string { return puppet.NextBatch }
  289. func (puppet *Puppet) LoadRoom(roomID string) *mautrix.Room { return nil }