custompuppet.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. "encoding/json"
  19. "fmt"
  20. "strings"
  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. )
  27. var (
  28. ErrNoCustomMXID = errors.New("no custom mxid set")
  29. ErrMismatchingMXID = errors.New("whoami result does not match custom mxid")
  30. )
  31. func (puppet *Puppet) SwitchCustomMXID(accessToken string, mxid string) error {
  32. prevCustomMXID := puppet.CustomMXID
  33. if puppet.customIntent != nil {
  34. puppet.stopSyncing()
  35. }
  36. puppet.CustomMXID = mxid
  37. puppet.AccessToken = accessToken
  38. err := puppet.StartCustomMXID()
  39. if err != nil {
  40. return err
  41. }
  42. if len(prevCustomMXID) > 0 {
  43. delete(puppet.bridge.puppetsByCustomMXID, prevCustomMXID)
  44. }
  45. if len(puppet.CustomMXID) > 0 {
  46. puppet.bridge.puppetsByCustomMXID[puppet.CustomMXID] = puppet
  47. }
  48. puppet.Update()
  49. // TODO leave rooms with default puppet
  50. return nil
  51. }
  52. func (puppet *Puppet) newCustomIntent() (*appservice.IntentAPI, error) {
  53. if len(puppet.CustomMXID) == 0 {
  54. return nil, ErrNoCustomMXID
  55. }
  56. client, err := mautrix.NewClient(puppet.bridge.AS.HomeserverURL, puppet.CustomMXID, puppet.AccessToken)
  57. if err != nil {
  58. return nil, err
  59. }
  60. client.Logger = puppet.bridge.AS.Log.Sub(puppet.CustomMXID)
  61. client.Syncer = puppet
  62. client.Store = puppet
  63. ia := puppet.bridge.AS.NewIntentAPI("custom")
  64. ia.Client = client
  65. ia.Localpart = puppet.CustomMXID[1:strings.IndexRune(puppet.CustomMXID, ':')]
  66. ia.UserID = puppet.CustomMXID
  67. ia.IsCustomPuppet = true
  68. return ia, nil
  69. }
  70. func (puppet *Puppet) clearCustomMXID() {
  71. puppet.CustomMXID = ""
  72. puppet.AccessToken = ""
  73. puppet.customIntent = nil
  74. puppet.customTypingIn = nil
  75. puppet.customUser = nil
  76. }
  77. func (puppet *Puppet) StartCustomMXID() error {
  78. if len(puppet.CustomMXID) == 0 {
  79. puppet.clearCustomMXID()
  80. return nil
  81. }
  82. intent, err := puppet.newCustomIntent()
  83. if err != nil {
  84. puppet.clearCustomMXID()
  85. return err
  86. }
  87. urlPath := intent.BuildURL("account", "whoami")
  88. var resp struct{ UserID string `json:"user_id"` }
  89. _, err = intent.MakeRequest("GET", urlPath, nil, &resp)
  90. if err != nil {
  91. puppet.clearCustomMXID()
  92. return err
  93. }
  94. if resp.UserID != puppet.CustomMXID {
  95. puppet.clearCustomMXID()
  96. return ErrMismatchingMXID
  97. }
  98. puppet.customIntent = intent
  99. puppet.customTypingIn = make(map[string]bool)
  100. puppet.customUser = puppet.bridge.GetUserByMXID(puppet.CustomMXID)
  101. puppet.startSyncing()
  102. return nil
  103. }
  104. func (puppet *Puppet) startSyncing() {
  105. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  106. return
  107. }
  108. go func() {
  109. puppet.log.Debugln("Starting syncing...")
  110. puppet.customIntent.SyncPresence = "offline"
  111. err := puppet.customIntent.Sync()
  112. if err != nil {
  113. puppet.log.Errorln("Fatal error syncing:", err)
  114. }
  115. }()
  116. }
  117. func (puppet *Puppet) stopSyncing() {
  118. if !puppet.bridge.Config.Bridge.SyncWithCustomPuppets {
  119. return
  120. }
  121. puppet.customIntent.StopSync()
  122. }
  123. func (puppet *Puppet) ProcessResponse(resp *mautrix.RespSync, since string) error {
  124. if !puppet.customUser.Connected {
  125. puppet.log.Warnln("Skipping sync processing: custom user not connected to whatsapp")
  126. return nil
  127. }
  128. for roomID, events := range resp.Rooms.Join {
  129. portal := puppet.bridge.GetPortalByMXID(roomID)
  130. if portal == nil {
  131. continue
  132. }
  133. for _, event := range events.Ephemeral.Events {
  134. switch event.Type {
  135. case mautrix.EphemeralEventReceipt:
  136. go puppet.handleReceiptEvent(portal, event)
  137. case mautrix.EphemeralEventTyping:
  138. go puppet.handleTypingEvent(portal, event)
  139. }
  140. }
  141. }
  142. for _, event := range resp.Presence.Events {
  143. if event.Sender != puppet.CustomMXID {
  144. continue
  145. }
  146. go puppet.handlePresenceEvent(event)
  147. }
  148. return nil
  149. }
  150. func (puppet *Puppet) handlePresenceEvent(event *mautrix.Event) {
  151. presence := whatsapp.PresenceAvailable
  152. if event.Content.Raw["presence"].(string) != "online" {
  153. presence = whatsapp.PresenceUnavailable
  154. puppet.customUser.log.Infoln("Marking offline")
  155. } else {
  156. puppet.customUser.log.Infoln("Marking online")
  157. }
  158. _, err := puppet.customUser.Conn.Presence("", presence)
  159. if err != nil {
  160. puppet.customUser.log.Warnln("Failed to set presence:", err)
  161. }
  162. }
  163. func (puppet *Puppet) handleReceiptEvent(portal *Portal, event *mautrix.Event) {
  164. for eventID, rawReceipts := range event.Content.Raw {
  165. if receipts, ok := rawReceipts.(map[string]interface{}); !ok {
  166. continue
  167. } else if readReceipt, ok := receipts["m.read"].(map[string]interface{}); !ok {
  168. continue
  169. } else if _, ok = readReceipt[puppet.CustomMXID].(map[string]interface{}); !ok {
  170. continue
  171. }
  172. message := puppet.bridge.DB.Message.GetByMXID(eventID)
  173. if message == nil {
  174. continue
  175. }
  176. puppet.customUser.log.Infofln("Marking %s/%s in %s/%s as read", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  177. _, err := puppet.customUser.Conn.Read(portal.Key.JID, message.JID)
  178. if err != nil {
  179. puppet.customUser.log.Warnln("Error marking read:", err)
  180. }
  181. }
  182. }
  183. func (puppet *Puppet) handleTypingEvent(portal *Portal, event *mautrix.Event) {
  184. isTyping := false
  185. for _, userID := range event.Content.TypingUserIDs {
  186. if userID == puppet.CustomMXID {
  187. isTyping = true
  188. break
  189. }
  190. }
  191. if puppet.customTypingIn[event.RoomID] != isTyping {
  192. puppet.customTypingIn[event.RoomID] = isTyping
  193. presence := whatsapp.PresenceComposing
  194. if !isTyping {
  195. puppet.customUser.log.Infofln("Marking not typing in %s/%s", portal.Key.JID, portal.MXID)
  196. presence = whatsapp.PresencePaused
  197. } else {
  198. puppet.customUser.log.Infofln("Marking typing in %s/%s", portal.Key.JID, portal.MXID)
  199. }
  200. _, err := puppet.customUser.Conn.Presence(portal.Key.JID, presence)
  201. if err != nil {
  202. puppet.customUser.log.Warnln("Error setting typing:", err)
  203. }
  204. }
  205. }
  206. func (puppet *Puppet) OnFailedSync(res *mautrix.RespSync, err error) (time.Duration, error) {
  207. puppet.log.Warnln("Sync error:", err)
  208. return 10 * time.Second, nil
  209. }
  210. func (puppet *Puppet) GetFilterJSON(_ string) json.RawMessage {
  211. mxid, _ := json.Marshal(puppet.CustomMXID)
  212. return json.RawMessage(fmt.Sprintf(`{
  213. "account_data": { "types": [] },
  214. "presence": {
  215. "senders": [
  216. %s
  217. ],
  218. "types": [
  219. "m.presence"
  220. ]
  221. },
  222. "room": {
  223. "ephemeral": {
  224. "types": [
  225. "m.typing",
  226. "m.receipt"
  227. ]
  228. },
  229. "include_leave": false,
  230. "account_data": { "types": [] },
  231. "state": { "types": [] },
  232. "timeline": { "types": [] }
  233. }
  234. }`, mxid))
  235. }
  236. func (puppet *Puppet) SaveFilterID(_, _ string) {}
  237. func (puppet *Puppet) SaveNextBatch(_, nbt string) { puppet.NextBatch = nbt; puppet.Update() }
  238. func (puppet *Puppet) SaveRoom(room *mautrix.Room) {}
  239. func (puppet *Puppet) LoadFilterID(_ string) string { return "" }
  240. func (puppet *Puppet) LoadNextBatch(_ string) string { return puppet.NextBatch }
  241. func (puppet *Puppet) LoadRoom(roomID string) *mautrix.Room { return nil }