user.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "context"
  19. "encoding/json"
  20. "errors"
  21. "fmt"
  22. "net/http"
  23. "sync"
  24. "time"
  25. log "maunium.net/go/maulogger/v2"
  26. "go.mau.fi/whatsmeow/appstate"
  27. waProto "go.mau.fi/whatsmeow/binary/proto"
  28. "maunium.net/go/mautrix/appservice"
  29. "maunium.net/go/mautrix/pushrules"
  30. "go.mau.fi/whatsmeow"
  31. "go.mau.fi/whatsmeow/store"
  32. "go.mau.fi/whatsmeow/types"
  33. "go.mau.fi/whatsmeow/types/events"
  34. waLog "go.mau.fi/whatsmeow/util/log"
  35. "maunium.net/go/mautrix"
  36. "maunium.net/go/mautrix/event"
  37. "maunium.net/go/mautrix/format"
  38. "maunium.net/go/mautrix/id"
  39. "maunium.net/go/mautrix-whatsapp/database"
  40. )
  41. type User struct {
  42. *database.User
  43. Client *whatsmeow.Client
  44. Session *store.Device
  45. bridge *Bridge
  46. log log.Logger
  47. Admin bool
  48. Whitelisted bool
  49. RelaybotWhitelisted bool
  50. IsRelaybot bool
  51. mgmtCreateLock sync.Mutex
  52. connLock sync.Mutex
  53. historySyncs chan *events.HistorySync
  54. prevBridgeStatus *BridgeState
  55. }
  56. func (bridge *Bridge) GetUserByMXID(userID id.UserID) *User {
  57. _, isPuppet := bridge.ParsePuppetMXID(userID)
  58. if isPuppet || userID == bridge.Bot.UserID {
  59. return nil
  60. }
  61. bridge.usersLock.Lock()
  62. defer bridge.usersLock.Unlock()
  63. user, ok := bridge.usersByMXID[userID]
  64. if !ok {
  65. return bridge.loadDBUser(bridge.DB.User.GetByMXID(userID), &userID)
  66. }
  67. return user
  68. }
  69. func (bridge *Bridge) GetUserByJID(jid types.JID) *User {
  70. bridge.usersLock.Lock()
  71. defer bridge.usersLock.Unlock()
  72. user, ok := bridge.usersByUsername[jid.User]
  73. if !ok {
  74. return bridge.loadDBUser(bridge.DB.User.GetByUsername(jid.User), nil)
  75. }
  76. return user
  77. }
  78. func (user *User) addToJIDMap() {
  79. user.bridge.usersLock.Lock()
  80. user.bridge.usersByUsername[user.JID.User] = user
  81. user.bridge.usersLock.Unlock()
  82. }
  83. func (user *User) removeFromJIDMap(state BridgeStateEvent) {
  84. user.bridge.usersLock.Lock()
  85. jidUser, ok := user.bridge.usersByUsername[user.JID.User]
  86. if ok && user == jidUser {
  87. delete(user.bridge.usersByUsername, user.JID.User)
  88. }
  89. user.bridge.usersLock.Unlock()
  90. user.bridge.Metrics.TrackLoginState(user.JID, false)
  91. user.sendBridgeState(BridgeState{StateEvent: state, Error: WANotLoggedIn})
  92. }
  93. func (bridge *Bridge) GetAllUsers() []*User {
  94. bridge.usersLock.Lock()
  95. defer bridge.usersLock.Unlock()
  96. dbUsers := bridge.DB.User.GetAll()
  97. output := make([]*User, len(dbUsers))
  98. for index, dbUser := range dbUsers {
  99. user, ok := bridge.usersByMXID[dbUser.MXID]
  100. if !ok {
  101. user = bridge.loadDBUser(dbUser, nil)
  102. }
  103. output[index] = user
  104. }
  105. return output
  106. }
  107. func (bridge *Bridge) loadDBUser(dbUser *database.User, mxid *id.UserID) *User {
  108. if dbUser == nil {
  109. if mxid == nil {
  110. return nil
  111. }
  112. dbUser = bridge.DB.User.New()
  113. dbUser.MXID = *mxid
  114. dbUser.Insert()
  115. }
  116. user := bridge.NewUser(dbUser)
  117. bridge.usersByMXID[user.MXID] = user
  118. if !user.JID.IsEmpty() {
  119. var err error
  120. user.Session, err = bridge.WAContainer.GetDevice(user.JID)
  121. if err != nil {
  122. user.log.Errorfln("Failed to load user's whatsapp session: %v", err)
  123. } else if user.Session == nil {
  124. user.log.Warnfln("Didn't find session data for %s, treating user as logged out", user.JID)
  125. user.JID = types.EmptyJID
  126. user.Update()
  127. } else {
  128. bridge.usersByUsername[user.JID.User] = user
  129. }
  130. }
  131. if len(user.ManagementRoom) > 0 {
  132. bridge.managementRooms[user.ManagementRoom] = user
  133. }
  134. return user
  135. }
  136. func (user *User) GetPortals() []*Portal {
  137. // FIXME
  138. //keys := user.User.GetPortalKeys()
  139. //portals := make([]*Portal, len(keys))
  140. //
  141. //user.bridge.portalsLock.Lock()
  142. //for i, key := range keys {
  143. // portal, ok := user.bridge.portalsByJID[key]
  144. // if !ok {
  145. // portal = user.bridge.loadDBPortal(user.bridge.DB.Portal.GetByJID(key), &key)
  146. // }
  147. // portals[i] = portal
  148. //}
  149. //user.bridge.portalsLock.Unlock()
  150. //return portals
  151. return nil
  152. }
  153. func (bridge *Bridge) NewUser(dbUser *database.User) *User {
  154. user := &User{
  155. User: dbUser,
  156. bridge: bridge,
  157. log: bridge.Log.Sub("User").Sub(string(dbUser.MXID)),
  158. historySyncs: make(chan *events.HistorySync, 32),
  159. IsRelaybot: false,
  160. }
  161. user.RelaybotWhitelisted = user.bridge.Config.Bridge.Permissions.IsRelaybotWhitelisted(user.MXID)
  162. user.Whitelisted = user.bridge.Config.Bridge.Permissions.IsWhitelisted(user.MXID)
  163. user.Admin = user.bridge.Config.Bridge.Permissions.IsAdmin(user.MXID)
  164. go func() {
  165. for evt := range user.historySyncs {
  166. if evt == nil {
  167. return
  168. }
  169. user.handleHistorySync(evt.Data)
  170. }
  171. }()
  172. return user
  173. }
  174. func (user *User) GetManagementRoom() id.RoomID {
  175. if len(user.ManagementRoom) == 0 {
  176. user.mgmtCreateLock.Lock()
  177. defer user.mgmtCreateLock.Unlock()
  178. if len(user.ManagementRoom) > 0 {
  179. return user.ManagementRoom
  180. }
  181. resp, err := user.bridge.Bot.CreateRoom(&mautrix.ReqCreateRoom{
  182. Topic: "WhatsApp bridge notices",
  183. IsDirect: true,
  184. })
  185. if err != nil {
  186. user.log.Errorln("Failed to auto-create management room:", err)
  187. } else {
  188. user.SetManagementRoom(resp.RoomID)
  189. }
  190. }
  191. return user.ManagementRoom
  192. }
  193. func (user *User) SetManagementRoom(roomID id.RoomID) {
  194. existingUser, ok := user.bridge.managementRooms[roomID]
  195. if ok {
  196. existingUser.ManagementRoom = ""
  197. existingUser.Update()
  198. }
  199. user.ManagementRoom = roomID
  200. user.bridge.managementRooms[user.ManagementRoom] = user
  201. user.Update()
  202. }
  203. type waLogger struct{ l log.Logger }
  204. func (w *waLogger) Debugf(msg string, args ...interface{}) { w.l.Debugfln(msg, args...) }
  205. func (w *waLogger) Infof(msg string, args ...interface{}) { w.l.Infofln(msg, args...) }
  206. func (w *waLogger) Warnf(msg string, args ...interface{}) { w.l.Warnfln(msg, args...) }
  207. func (w *waLogger) Errorf(msg string, args ...interface{}) { w.l.Errorfln(msg, args...) }
  208. func (w *waLogger) Sub(module string) waLog.Logger { return &waLogger{l: w.l.Sub(module)} }
  209. var ErrAlreadyLoggedIn = errors.New("already logged in")
  210. func (user *User) Login(ctx context.Context) (<-chan whatsmeow.QRChannelItem, error) {
  211. user.connLock.Lock()
  212. defer user.connLock.Unlock()
  213. if user.Session != nil {
  214. return nil, ErrAlreadyLoggedIn
  215. } else if user.Client != nil {
  216. user.unlockedDeleteConnection()
  217. }
  218. newSession := user.bridge.WAContainer.NewDevice()
  219. newSession.Log = &waLogger{user.log.Sub("Session")}
  220. user.Client = whatsmeow.NewClient(newSession, &waLogger{user.log.Sub("Client")})
  221. qrChan, err := user.Client.GetQRChannel(ctx)
  222. if err != nil {
  223. return nil, fmt.Errorf("failed to get QR channel: %w", err)
  224. }
  225. err = user.Client.Connect()
  226. if err != nil {
  227. return nil, fmt.Errorf("failed to connect to WhatsApp: %w", err)
  228. }
  229. return qrChan, nil
  230. }
  231. func (user *User) Connect() bool {
  232. user.connLock.Lock()
  233. defer user.connLock.Unlock()
  234. if user.Client != nil {
  235. return user.Client.IsConnected()
  236. } else if user.Session == nil {
  237. return false
  238. }
  239. user.log.Debugln("Connecting to WhatsApp")
  240. user.sendBridgeState(BridgeState{StateEvent: StateConnecting, Error: WAConnecting})
  241. user.Client = whatsmeow.NewClient(user.Session, &waLogger{user.log.Sub("Client")})
  242. user.Client.AddEventHandler(user.HandleEvent)
  243. err := user.Client.Connect()
  244. if err != nil {
  245. user.log.Warnln("Error connecting to WhatsApp:", err)
  246. return false
  247. }
  248. return true
  249. }
  250. func (user *User) unlockedDeleteConnection() {
  251. if user.Client == nil {
  252. return
  253. }
  254. user.Client.Disconnect()
  255. user.Client.RemoveEventHandlers()
  256. user.Client = nil
  257. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  258. }
  259. func (user *User) DeleteConnection() {
  260. user.connLock.Lock()
  261. defer user.connLock.Unlock()
  262. user.unlockedDeleteConnection()
  263. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  264. }
  265. func (user *User) HasSession() bool {
  266. return user.Session != nil
  267. }
  268. func (user *User) DeleteSession() {
  269. if user.Session != nil {
  270. err := user.Session.Delete()
  271. if err != nil {
  272. user.log.Warnln("Failed to delete session:", err)
  273. }
  274. user.Session = nil
  275. }
  276. if !user.JID.IsEmpty() {
  277. user.JID = types.EmptyJID
  278. user.Update()
  279. }
  280. }
  281. func (user *User) IsConnected() bool {
  282. return user.Client != nil && user.Client.IsConnected()
  283. }
  284. func (user *User) IsLoggedIn() bool {
  285. return user.IsConnected() && user.Client.IsLoggedIn
  286. }
  287. func (user *User) tryAutomaticDoublePuppeting() {
  288. if !user.bridge.Config.CanDoublePuppet(user.MXID) {
  289. return
  290. }
  291. user.log.Debugln("Checking if double puppeting needs to be enabled")
  292. puppet := user.bridge.GetPuppetByJID(user.JID)
  293. if len(puppet.CustomMXID) > 0 {
  294. user.log.Debugln("User already has double-puppeting enabled")
  295. // Custom puppet already enabled
  296. return
  297. }
  298. accessToken, err := puppet.loginWithSharedSecret(user.MXID)
  299. if err != nil {
  300. user.log.Warnln("Failed to login with shared secret:", err)
  301. return
  302. }
  303. err = puppet.SwitchCustomMXID(accessToken, user.MXID)
  304. if err != nil {
  305. puppet.log.Warnln("Failed to switch to auto-logined custom puppet:", err)
  306. return
  307. }
  308. user.log.Infoln("Successfully automatically enabled custom puppet")
  309. }
  310. func (user *User) sendBridgeNotice(formatString string, args ...interface{}) {
  311. notice := fmt.Sprintf(formatString, args...)
  312. _, err := user.bridge.Bot.SendNotice(user.GetManagementRoom(), notice)
  313. if err != nil {
  314. user.log.Warnf("Failed to send bridge notice \"%s\": %v", notice, err)
  315. }
  316. }
  317. func (user *User) sendMarkdownBridgeAlert(formatString string, args ...interface{}) {
  318. notice := fmt.Sprintf(formatString, args...)
  319. content := format.RenderMarkdown(notice, true, false)
  320. _, err := user.bridge.Bot.SendMessageEvent(user.GetManagementRoom(), event.EventMessage, content)
  321. if err != nil {
  322. user.log.Warnf("Failed to send bridge alert \"%s\": %v", notice, err)
  323. }
  324. }
  325. func (user *User) handleHistorySync(evt *waProto.HistorySync) {
  326. if evt.GetSyncType() != waProto.HistorySync_RECENT && evt.GetSyncType() != waProto.HistorySync_FULL {
  327. return
  328. }
  329. user.log.Infofln("Handling history sync with type %s, chunk order %d, progress %d%%", evt.GetSyncType(), evt.GetChunkOrder(), evt.GetProgress())
  330. for _, conv := range evt.GetConversations() {
  331. jid, err := types.ParseJID(conv.GetId())
  332. if err != nil {
  333. user.log.Warnfln("Failed to parse chat JID '%s' in history sync: %v", conv.GetId(), err)
  334. continue
  335. }
  336. portal := user.GetPortalByJID(jid)
  337. err = portal.CreateMatrixRoom(user)
  338. if err != nil {
  339. user.log.Warnfln("Failed to create room for %s during backfill: %v", portal.Key.JID, err)
  340. continue
  341. }
  342. portal.backfill(user, conv.GetMessages())
  343. }
  344. }
  345. func (user *User) HandleEvent(event interface{}) {
  346. switch v := event.(type) {
  347. case *events.LoggedOut:
  348. go user.handleLoggedOut()
  349. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  350. user.bridge.Metrics.TrackLoginState(user.JID, false)
  351. case *events.Connected:
  352. go user.sendBridgeState(BridgeState{StateEvent: StateConnected})
  353. user.bridge.Metrics.TrackConnectionState(user.JID, true)
  354. user.bridge.Metrics.TrackLoginState(user.JID, true)
  355. go func() {
  356. err := user.Client.SendPresence(types.PresenceUnavailable)
  357. if err != nil {
  358. user.log.Warnln("Failed to send initial presence:", err)
  359. }
  360. }()
  361. go user.tryAutomaticDoublePuppeting()
  362. case *events.AppStateSyncComplete:
  363. if len(user.Client.Store.PushName) > 0 && v.Name == appstate.WAPatchCriticalBlock {
  364. err := user.Client.SendPresence(types.PresenceUnavailable)
  365. if err != nil {
  366. user.log.Warnln("Failed to send presence after app state sync:", err)
  367. }
  368. }
  369. case *events.PushNameSetting:
  370. // Send presence available when connecting and when the pushname is changed.
  371. // This makes sure that outgoing messages always have the right pushname.
  372. err := user.Client.SendPresence(types.PresenceUnavailable)
  373. if err != nil {
  374. user.log.Warnln("Failed to send presence after push name update:", err)
  375. }
  376. case *events.PairSuccess:
  377. user.JID = v.ID
  378. user.addToJIDMap()
  379. user.Update()
  380. user.Session = user.Client.Store
  381. case *events.ConnectFailure, *events.StreamError:
  382. go user.sendBridgeState(BridgeState{StateEvent: StateUnknownError})
  383. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  384. case *events.Disconnected:
  385. go user.sendBridgeState(BridgeState{StateEvent: StateTransientDisconnect})
  386. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  387. case *events.Contact:
  388. go user.syncPuppet(v.JID)
  389. case *events.PushName:
  390. go user.syncPuppet(v.JID)
  391. case *events.Receipt:
  392. go user.handleReceipt(v)
  393. case *events.ChatPresence:
  394. go user.handleChatPresence(v)
  395. case *events.Message:
  396. portal := user.GetPortalByJID(v.Info.Chat)
  397. portal.messages <- PortalMessage{evt: v, source: user}
  398. case *events.UndecryptableMessage:
  399. portal := user.GetPortalByJID(v.Info.Chat)
  400. portal.messages <- PortalMessage{undecryptable: v, source: user}
  401. case *events.HistorySync:
  402. user.historySyncs <- v
  403. case *events.Mute:
  404. portal := user.bridge.GetPortalByJID(user.PortalKey(v.JID))
  405. if portal != nil {
  406. var mutedUntil time.Time
  407. if v.Action.GetMuted() {
  408. mutedUntil = time.Unix(v.Action.GetMuteEndTimestamp(), 0)
  409. }
  410. go user.updateChatMute(nil, portal, mutedUntil)
  411. }
  412. case *events.Archive:
  413. portal := user.bridge.GetPortalByJID(user.PortalKey(v.JID))
  414. if portal != nil {
  415. go user.updateChatTag(nil, portal, user.bridge.Config.Bridge.ArchiveTag, v.Action.GetArchived())
  416. }
  417. case *events.Pin:
  418. portal := user.bridge.GetPortalByJID(user.PortalKey(v.JID))
  419. if portal != nil {
  420. go user.updateChatTag(nil, portal, user.bridge.Config.Bridge.PinnedTag, v.Action.GetPinned())
  421. }
  422. case *events.AppState:
  423. // Ignore
  424. default:
  425. user.log.Debugfln("Unknown type of event in HandleEvent: %T", v)
  426. }
  427. }
  428. func (user *User) updateChatMute(intent *appservice.IntentAPI, portal *Portal, mutedUntil time.Time) {
  429. if len(portal.MXID) == 0 || !user.bridge.Config.Bridge.MuteBridging {
  430. return
  431. } else if intent == nil {
  432. doublePuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
  433. if doublePuppet == nil || doublePuppet.CustomIntent() == nil {
  434. return
  435. }
  436. intent = doublePuppet.CustomIntent()
  437. }
  438. var err error
  439. if mutedUntil.IsZero() && mutedUntil.Before(time.Now()) {
  440. user.log.Debugfln("Portal %s is muted until %d, unmuting...", portal.MXID, mutedUntil)
  441. err = intent.DeletePushRule("global", pushrules.RoomRule, string(portal.MXID))
  442. } else {
  443. user.log.Debugfln("Portal %s is muted until %d, muting...", portal.MXID, mutedUntil)
  444. err = intent.PutPushRule("global", pushrules.RoomRule, string(portal.MXID), &mautrix.ReqPutPushRule{
  445. Actions: []pushrules.PushActionType{pushrules.ActionDontNotify},
  446. })
  447. }
  448. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  449. user.log.Warnfln("Failed to update push rule for %s through double puppet: %v", portal.MXID, err)
  450. }
  451. }
  452. type CustomTagData struct {
  453. Order json.Number `json:"order"`
  454. DoublePuppet bool `json:"net.maunium.whatsapp.puppet"`
  455. }
  456. type CustomTagEventContent struct {
  457. Tags map[string]CustomTagData `json:"tags"`
  458. }
  459. func (user *User) updateChatTag(intent *appservice.IntentAPI, portal *Portal, tag string, active bool) {
  460. if len(portal.MXID) == 0 || len(tag) == 0 {
  461. return
  462. } else if intent == nil {
  463. doublePuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
  464. if doublePuppet == nil || doublePuppet.CustomIntent() == nil {
  465. return
  466. }
  467. intent = doublePuppet.CustomIntent()
  468. }
  469. var existingTags CustomTagEventContent
  470. err := intent.GetTagsWithCustomData(portal.MXID, &existingTags)
  471. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  472. user.log.Warnfln("Failed to get tags of %s: %v", portal.MXID, err)
  473. }
  474. currentTag, ok := existingTags.Tags[tag]
  475. if active && !ok {
  476. user.log.Debugln("Adding tag", tag, "to", portal.MXID)
  477. data := CustomTagData{"0.5", true}
  478. err = intent.AddTagWithCustomData(portal.MXID, tag, &data)
  479. } else if !active && ok && currentTag.DoublePuppet {
  480. user.log.Debugln("Removing tag", tag, "from", portal.MXID)
  481. err = intent.RemoveTag(portal.MXID, tag)
  482. } else {
  483. err = nil
  484. }
  485. if err != nil {
  486. user.log.Warnfln("Failed to update tag %s for %s through double puppet: %v", tag, portal.MXID, err)
  487. }
  488. }
  489. type CustomReadReceipt struct {
  490. Timestamp int64 `json:"ts,omitempty"`
  491. DoublePuppet bool `json:"net.maunium.whatsapp.puppet,omitempty"`
  492. }
  493. func (user *User) syncChatDoublePuppetDetails(doublePuppet *Puppet, portal *Portal, justCreated bool) {
  494. if doublePuppet == nil || doublePuppet.CustomIntent() == nil || len(portal.MXID) == 0 {
  495. return
  496. }
  497. intent := doublePuppet.CustomIntent()
  498. // FIXME this might not be possible to do anymore
  499. //if chat.UnreadCount == 0 && (justCreated || !user.bridge.Config.Bridge.MarkReadOnlyOnCreate) {
  500. // lastMessage := user.bridge.DB.Message.GetLastInChatBefore(chat.Portal.Key, chat.ReceivedAt.Unix())
  501. // if lastMessage != nil {
  502. // err := intent.MarkReadWithContent(chat.Portal.MXID, lastMessage.MXID, &CustomReadReceipt{DoublePuppet: true})
  503. // if err != nil {
  504. // user.log.Warnfln("Failed to mark %s in %s as read after backfill: %v", lastMessage.MXID, chat.Portal.MXID, err)
  505. // }
  506. // }
  507. //} else if chat.UnreadCount == -1 {
  508. // user.log.Debugfln("Invalid unread count (missing field?) in chat info %+v", chat.Source)
  509. //}
  510. if justCreated || !user.bridge.Config.Bridge.TagOnlyOnCreate {
  511. chat, err := user.Client.Store.ChatSettings.GetChatSettings(portal.Key.JID)
  512. if err != nil {
  513. user.log.Warnfln("Failed to get settings of %s: %v", portal.Key.JID, err)
  514. return
  515. }
  516. user.updateChatMute(intent, portal, chat.MutedUntil)
  517. user.updateChatTag(intent, portal, user.bridge.Config.Bridge.ArchiveTag, chat.Archived)
  518. user.updateChatTag(intent, portal, user.bridge.Config.Bridge.PinnedTag, chat.Pinned)
  519. }
  520. }
  521. //func (user *User) syncPortal(chat Chat) {
  522. // // Don't sync unless chat meta sync is enabled or portal doesn't exist
  523. // if user.bridge.Config.Bridge.ChatMetaSync || len(chat.Portal.MXID) == 0 {
  524. // failedToCreate := chat.Portal.Sync(user, chat.Contact)
  525. // if failedToCreate {
  526. // return
  527. // }
  528. // }
  529. // err := chat.Portal.BackfillHistory(user, chat.LastMessageTime)
  530. // if err != nil {
  531. // chat.Portal.log.Errorln("Error backfilling history:", err)
  532. // }
  533. //}
  534. //
  535. //func (user *User) syncPortals(chatMap map[string]whatsapp.Chat, createAll bool) {
  536. // // TODO use contexts instead of checking if user.Conn is the same?
  537. // connAtStart := user.Conn
  538. //
  539. // chats := user.collectChatList(chatMap)
  540. //
  541. // limit := user.bridge.Config.Bridge.InitialChatSync
  542. // if limit < 0 {
  543. // limit = len(chats)
  544. // }
  545. // if user.Conn != connAtStart {
  546. // user.log.Debugln("Connection seems to have changed before sync, cancelling")
  547. // return
  548. // }
  549. // now := time.Now().Unix()
  550. // user.log.Infoln("Syncing portals")
  551. // doublePuppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
  552. // for i, chat := range chats {
  553. // if chat.LastMessageTime+user.bridge.Config.Bridge.SyncChatMaxAge < now {
  554. // break
  555. // }
  556. // create := (chat.LastMessageTime >= user.LastConnection && user.LastConnection > 0) || i < limit
  557. // if len(chat.Portal.MXID) > 0 || create || createAll {
  558. // user.log.Debugfln("Syncing chat %+v", chat.Chat.Source)
  559. // justCreated := len(chat.Portal.MXID) == 0
  560. // user.syncPortal(chat)
  561. // user.syncChatDoublePuppetDetails(doublePuppet, chat, justCreated)
  562. // }
  563. // }
  564. // if user.Conn != connAtStart {
  565. // user.log.Debugln("Connection seems to have changed during sync, cancelling")
  566. // return
  567. // }
  568. // user.UpdateDirectChats(nil)
  569. //
  570. // user.log.Infoln("Finished syncing portals")
  571. // select {
  572. // case user.syncPortalsDone <- struct{}{}:
  573. // default:
  574. // }
  575. //}
  576. func (user *User) getDirectChats() map[id.UserID][]id.RoomID {
  577. res := make(map[id.UserID][]id.RoomID)
  578. privateChats := user.bridge.DB.Portal.FindPrivateChats(user.JID.ToNonAD())
  579. for _, portal := range privateChats {
  580. if len(portal.MXID) > 0 {
  581. res[user.bridge.FormatPuppetMXID(portal.Key.JID)] = []id.RoomID{portal.MXID}
  582. }
  583. }
  584. return res
  585. }
  586. func (user *User) UpdateDirectChats(chats map[id.UserID][]id.RoomID) {
  587. if !user.bridge.Config.Bridge.SyncDirectChatList {
  588. return
  589. }
  590. puppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
  591. if puppet == nil || puppet.CustomIntent() == nil {
  592. return
  593. }
  594. intent := puppet.CustomIntent()
  595. method := http.MethodPatch
  596. if chats == nil {
  597. chats = user.getDirectChats()
  598. method = http.MethodPut
  599. }
  600. user.log.Debugln("Updating m.direct list on homeserver")
  601. var err error
  602. if user.bridge.Config.Homeserver.Asmux {
  603. urlPath := intent.BuildBaseURL("_matrix", "client", "unstable", "com.beeper.asmux", "dms")
  604. _, err = intent.MakeFullRequest(mautrix.FullRequest{
  605. Method: method,
  606. URL: urlPath,
  607. Headers: http.Header{"X-Asmux-Auth": {user.bridge.AS.Registration.AppToken}},
  608. RequestJSON: chats,
  609. })
  610. } else {
  611. existingChats := make(map[id.UserID][]id.RoomID)
  612. err = intent.GetAccountData(event.AccountDataDirectChats.Type, &existingChats)
  613. if err != nil {
  614. user.log.Warnln("Failed to get m.direct list to update it:", err)
  615. return
  616. }
  617. for userID, rooms := range existingChats {
  618. if _, ok := user.bridge.ParsePuppetMXID(userID); !ok {
  619. // This is not a ghost user, include it in the new list
  620. chats[userID] = rooms
  621. } else if _, ok := chats[userID]; !ok && method == http.MethodPatch {
  622. // This is a ghost user, but we're not replacing the whole list, so include it too
  623. chats[userID] = rooms
  624. }
  625. }
  626. err = intent.SetAccountData(event.AccountDataDirectChats.Type, &chats)
  627. }
  628. if err != nil {
  629. user.log.Warnln("Failed to update m.direct list:", err)
  630. }
  631. }
  632. func (user *User) handleLoggedOut() {
  633. user.JID = types.EmptyJID
  634. user.Update()
  635. user.sendMarkdownBridgeAlert("Connecting to WhatsApp failed as the device was logged out. Please link the bridge to your phone again.")
  636. user.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotLoggedIn})
  637. }
  638. func (user *User) PortalKey(jid types.JID) database.PortalKey {
  639. return database.NewPortalKey(jid, user.JID)
  640. }
  641. func (user *User) GetPortalByJID(jid types.JID) *Portal {
  642. return user.bridge.GetPortalByJID(user.PortalKey(jid))
  643. }
  644. func (user *User) syncPuppet(jid types.JID) {
  645. user.bridge.GetPuppetByJID(jid).SyncContact(user, false)
  646. }
  647. //func (user *User) HandlePresence(info whatsapp.PresenceEvent) {
  648. // puppet := user.bridge.GetPuppetByJID(info.SenderJID)
  649. // switch info.Status {
  650. // case whatsapp.PresenceUnavailable:
  651. // _ = puppet.DefaultIntent().SetPresence("offline")
  652. // case whatsapp.PresenceAvailable:
  653. // if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
  654. // portal := user.bridge.GetPortalByMXID(puppet.typingIn)
  655. // _, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
  656. // puppet.typingIn = ""
  657. // puppet.typingAt = 0
  658. // } else {
  659. // _ = puppet.DefaultIntent().SetPresence("online")
  660. // }
  661. // case whatsapp.PresenceComposing:
  662. // portal := user.GetPortalByJID(info.JID)
  663. // if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
  664. // if puppet.typingIn == portal.MXID {
  665. // return
  666. // }
  667. // _, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
  668. // }
  669. // if len(portal.MXID) > 0 {
  670. // puppet.typingIn = portal.MXID
  671. // puppet.typingAt = time.Now().Unix()
  672. // _, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, true, 15*1000)
  673. // }
  674. // }
  675. //}
  676. const WATypingTimeout = 15 * time.Second
  677. func (user *User) handleChatPresence(presence *events.ChatPresence) {
  678. puppet := user.bridge.GetPuppetByJID(presence.Sender)
  679. portal := user.GetPortalByJID(presence.Chat)
  680. if puppet == nil || portal == nil || len(portal.MXID) == 0 {
  681. return
  682. }
  683. if presence.State == types.ChatPresenceComposing {
  684. if puppet.typingIn != "" && puppet.typingAt.Add(WATypingTimeout).Before(time.Now()) {
  685. if puppet.typingIn == portal.MXID {
  686. return
  687. }
  688. _, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
  689. }
  690. _, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, true, WATypingTimeout.Milliseconds())
  691. puppet.typingIn = portal.MXID
  692. puppet.typingAt = time.Now()
  693. } else {
  694. _, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, false, 0)
  695. puppet.typingIn = ""
  696. }
  697. }
  698. func (user *User) handleReceipt(receipt *events.Receipt) {
  699. if receipt.Type != events.ReceiptTypeRead {
  700. return
  701. }
  702. portal := user.GetPortalByJID(receipt.Chat)
  703. if portal == nil || len(portal.MXID) == 0 {
  704. return
  705. }
  706. if receipt.IsFromMe {
  707. user.markSelfRead(portal, receipt.MessageID)
  708. } else {
  709. intent := user.bridge.GetPuppetByJID(receipt.Sender).IntentFor(portal)
  710. ok := user.markOtherRead(portal, intent, receipt.MessageID)
  711. if !ok {
  712. // Message not found, try any previous IDs
  713. for i := len(receipt.PreviousIDs) - 1; i >= 0; i-- {
  714. ok = user.markOtherRead(portal, intent, receipt.PreviousIDs[i])
  715. if ok {
  716. break
  717. }
  718. }
  719. }
  720. }
  721. }
  722. func (user *User) markOtherRead(portal *Portal, intent *appservice.IntentAPI, messageID types.MessageID) bool {
  723. msg := user.bridge.DB.Message.GetByJID(portal.Key, messageID)
  724. if msg == nil || msg.IsFakeMXID() {
  725. return false
  726. }
  727. err := intent.MarkReadWithContent(portal.MXID, msg.MXID, &CustomReadReceipt{DoublePuppet: intent.IsCustomPuppet})
  728. if err != nil {
  729. user.log.Warnfln("Failed to mark message %s as read by %s: %v", msg.MXID, intent.UserID, err)
  730. }
  731. return true
  732. }
  733. func (user *User) markSelfRead(portal *Portal, messageID types.MessageID) {
  734. puppet := user.bridge.GetPuppetByJID(user.JID)
  735. if puppet == nil {
  736. return
  737. }
  738. intent := puppet.CustomIntent()
  739. if intent == nil {
  740. return
  741. }
  742. var message *database.Message
  743. if messageID == "" {
  744. message = user.bridge.DB.Message.GetLastInChat(portal.Key)
  745. if message == nil {
  746. return
  747. }
  748. user.log.Debugfln("User read chat %s/%s in WhatsApp mobile (last known event: %s/%s)", portal.Key.JID, portal.MXID, message.JID, message.MXID)
  749. } else {
  750. message = user.bridge.DB.Message.GetByJID(portal.Key, messageID)
  751. if message == nil || message.IsFakeMXID() {
  752. return
  753. }
  754. user.log.Debugfln("User read message %s/%s in %s/%s in WhatsApp mobile", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  755. }
  756. err := intent.MarkReadWithContent(portal.MXID, message.MXID, &CustomReadReceipt{DoublePuppet: true})
  757. if err != nil {
  758. user.log.Warnfln("Failed to bridge own read receipt in %s: %v", portal.Key.JID, err)
  759. }
  760. }
  761. //func (user *User) HandleCommand(cmd whatsapp.JSONCommand) {
  762. // switch cmd.Type {
  763. // case whatsapp.CommandPicture:
  764. // if strings.HasSuffix(cmd.JID, whatsapp.NewUserSuffix) {
  765. // puppet := user.bridge.GetPuppetByJID(cmd.JID)
  766. // go puppet.UpdateAvatar(user, cmd.ProfilePicInfo)
  767. // } else if user.bridge.Config.Bridge.ChatMetaSync {
  768. // portal := user.GetPortalByJID(cmd.JID)
  769. // go portal.UpdateAvatar(user, cmd.ProfilePicInfo, true)
  770. // }
  771. // case whatsapp.CommandDisconnect:
  772. // if cmd.Kind == "replaced" {
  773. // user.cleanDisconnection = true
  774. // go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server because you opened another WhatsApp Web client.\n\n" +
  775. // "Use the `reconnect` command to disconnect the other client and resume bridging.")
  776. // } else {
  777. // user.log.Warnln("Unknown kind of disconnect:", string(cmd.Raw))
  778. // go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server (reason code: %s).\n\n"+
  779. // "Use the `reconnect` command to reconnect.", cmd.Kind)
  780. // }
  781. // }
  782. //}
  783. //func (user *User) HandleChatUpdate(cmd whatsapp.ChatUpdate) {
  784. // if cmd.Command != whatsapp.ChatUpdateCommandAction {
  785. // return
  786. // }
  787. //
  788. // portal := user.GetPortalByJID(cmd.JID)
  789. // if len(portal.MXID) == 0 {
  790. // if cmd.Data.Action == whatsapp.ChatActionIntroduce || cmd.Data.Action == whatsapp.ChatActionCreate {
  791. // go func() {
  792. // err := portal.CreateMatrixRoom(user)
  793. // if err != nil {
  794. // user.log.Errorln("Failed to create portal room after receiving join event:", err)
  795. // }
  796. // }()
  797. // }
  798. // return
  799. // }
  800. //
  801. // // These don't come down the message history :(
  802. // switch cmd.Data.Action {
  803. // case whatsapp.ChatActionAddTopic:
  804. // go portal.UpdateTopic(cmd.Data.AddTopic.Topic, cmd.Data.SenderJID, nil, true)
  805. // case whatsapp.ChatActionRemoveTopic:
  806. // go portal.UpdateTopic("", cmd.Data.SenderJID, nil, true)
  807. // case whatsapp.ChatActionRemove:
  808. // // We ignore leaving groups in the message history to avoid accidentally leaving rejoined groups,
  809. // // but if we get a real-time command that says we left, it should be safe to bridge it.
  810. // if !user.bridge.Config.Bridge.ChatMetaSync {
  811. // for _, jid := range cmd.Data.UserChange.JIDs {
  812. // if jid == user.JID {
  813. // go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
  814. // break
  815. // }
  816. // }
  817. // }
  818. // }
  819. //
  820. // if !user.bridge.Config.Bridge.ChatMetaSync {
  821. // // Ignore chat update commands, we're relying on the message history.
  822. // return
  823. // }
  824. //
  825. // switch cmd.Data.Action {
  826. // case whatsapp.ChatActionNameChange:
  827. // go portal.UpdateName(cmd.Data.NameChange.Name, cmd.Data.SenderJID, nil, true)
  828. // case whatsapp.ChatActionPromote:
  829. // go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, true)
  830. // case whatsapp.ChatActionDemote:
  831. // go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, false)
  832. // case whatsapp.ChatActionAnnounce:
  833. // go portal.RestrictMessageSending(cmd.Data.Announce)
  834. // case whatsapp.ChatActionRestrict:
  835. // go portal.RestrictMetadataChanges(cmd.Data.Restrict)
  836. // case whatsapp.ChatActionRemove:
  837. // go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
  838. // case whatsapp.ChatActionAdd:
  839. // go portal.HandleWhatsAppInvite(user, cmd.Data.SenderJID, nil, cmd.Data.UserChange.JIDs)
  840. // case whatsapp.ChatActionIntroduce:
  841. // if cmd.Data.SenderJID != "unknown" {
  842. // go portal.Sync(user, whatsapp.Contact{JID: portal.Key.JID})
  843. // }
  844. // }
  845. //}
  846. //
  847. //func (user *User) HandleJSONMessage(evt whatsapp.RawJSONMessage) {
  848. // if !json.Valid(evt.RawMessage) {
  849. // return
  850. // }
  851. // user.log.Debugfln("JSON message with tag %s: %s", evt.Tag, evt.RawMessage)
  852. // user.updateLastConnectionIfNecessary()
  853. //}
  854. func (user *User) NeedsRelaybot(portal *Portal) bool {
  855. return !user.HasSession() // || !user.IsInPortal(portal.Key)
  856. }