user.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "sync"
  26. "time"
  27. "github.com/skip2/go-qrcode"
  28. log "maunium.net/go/maulogger/v2"
  29. "github.com/Rhymen/go-whatsapp"
  30. waBinary "github.com/Rhymen/go-whatsapp/binary"
  31. waProto "github.com/Rhymen/go-whatsapp/binary/proto"
  32. "maunium.net/go/mautrix"
  33. "maunium.net/go/mautrix/event"
  34. "maunium.net/go/mautrix/format"
  35. "maunium.net/go/mautrix/id"
  36. "maunium.net/go/mautrix-whatsapp/database"
  37. "maunium.net/go/mautrix-whatsapp/types"
  38. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  39. )
  40. type User struct {
  41. *database.User
  42. Conn *whatsappExt.ExtendedConn
  43. bridge *Bridge
  44. log log.Logger
  45. Admin bool
  46. Whitelisted bool
  47. RelaybotWhitelisted bool
  48. IsRelaybot bool
  49. ConnectionErrors int
  50. CommunityID string
  51. cleanDisconnection bool
  52. batteryWarningsSent int
  53. lastReconnection int64
  54. chatListReceived chan struct{}
  55. syncPortalsDone chan struct{}
  56. messageInput chan PortalMessage
  57. messageOutput chan PortalMessage
  58. syncStart chan struct{}
  59. syncWait sync.WaitGroup
  60. mgmtCreateLock sync.Mutex
  61. connLock sync.Mutex
  62. }
  63. func (bridge *Bridge) GetUserByMXID(userID id.UserID) *User {
  64. _, isPuppet := bridge.ParsePuppetMXID(userID)
  65. if isPuppet || userID == bridge.Bot.UserID {
  66. return nil
  67. }
  68. bridge.usersLock.Lock()
  69. defer bridge.usersLock.Unlock()
  70. user, ok := bridge.usersByMXID[userID]
  71. if !ok {
  72. return bridge.loadDBUser(bridge.DB.User.GetByMXID(userID), &userID)
  73. }
  74. return user
  75. }
  76. func (bridge *Bridge) GetUserByJID(userID types.WhatsAppID) *User {
  77. bridge.usersLock.Lock()
  78. defer bridge.usersLock.Unlock()
  79. user, ok := bridge.usersByJID[userID]
  80. if !ok {
  81. return bridge.loadDBUser(bridge.DB.User.GetByJID(userID), nil)
  82. }
  83. return user
  84. }
  85. func (user *User) addToJIDMap() {
  86. user.bridge.usersLock.Lock()
  87. user.bridge.usersByJID[user.JID] = user
  88. user.bridge.usersLock.Unlock()
  89. }
  90. func (user *User) removeFromJIDMap() {
  91. user.bridge.usersLock.Lock()
  92. jidUser, ok := user.bridge.usersByJID[user.JID]
  93. if ok && user == jidUser {
  94. delete(user.bridge.usersByJID, user.JID)
  95. }
  96. user.bridge.usersLock.Unlock()
  97. user.bridge.Metrics.TrackLoginState(user.JID, false)
  98. }
  99. func (bridge *Bridge) GetAllUsers() []*User {
  100. bridge.usersLock.Lock()
  101. defer bridge.usersLock.Unlock()
  102. dbUsers := bridge.DB.User.GetAll()
  103. output := make([]*User, len(dbUsers))
  104. for index, dbUser := range dbUsers {
  105. user, ok := bridge.usersByMXID[dbUser.MXID]
  106. if !ok {
  107. user = bridge.loadDBUser(dbUser, nil)
  108. }
  109. output[index] = user
  110. }
  111. return output
  112. }
  113. func (bridge *Bridge) loadDBUser(dbUser *database.User, mxid *id.UserID) *User {
  114. if dbUser == nil {
  115. if mxid == nil {
  116. return nil
  117. }
  118. dbUser = bridge.DB.User.New()
  119. dbUser.MXID = *mxid
  120. dbUser.Insert()
  121. }
  122. user := bridge.NewUser(dbUser)
  123. bridge.usersByMXID[user.MXID] = user
  124. if len(user.JID) > 0 {
  125. bridge.usersByJID[user.JID] = user
  126. }
  127. if len(user.ManagementRoom) > 0 {
  128. bridge.managementRooms[user.ManagementRoom] = user
  129. }
  130. return user
  131. }
  132. func (user *User) GetPortals() []*Portal {
  133. keys := user.User.GetPortalKeys()
  134. portals := make([]*Portal, len(keys))
  135. user.bridge.portalsLock.Lock()
  136. for i, key := range keys {
  137. portal, ok := user.bridge.portalsByJID[key]
  138. if !ok {
  139. portal = user.bridge.loadDBPortal(user.bridge.DB.Portal.GetByJID(key), &key)
  140. }
  141. portals[i] = portal
  142. }
  143. user.bridge.portalsLock.Unlock()
  144. return portals
  145. }
  146. func (bridge *Bridge) NewUser(dbUser *database.User) *User {
  147. user := &User{
  148. User: dbUser,
  149. bridge: bridge,
  150. log: bridge.Log.Sub("User").Sub(string(dbUser.MXID)),
  151. IsRelaybot: false,
  152. chatListReceived: make(chan struct{}, 1),
  153. syncPortalsDone: make(chan struct{}, 1),
  154. syncStart: make(chan struct{}, 1),
  155. messageInput: make(chan PortalMessage),
  156. messageOutput: make(chan PortalMessage, bridge.Config.Bridge.UserMessageBuffer),
  157. }
  158. user.RelaybotWhitelisted = user.bridge.Config.Bridge.Permissions.IsRelaybotWhitelisted(user.MXID)
  159. user.Whitelisted = user.bridge.Config.Bridge.Permissions.IsWhitelisted(user.MXID)
  160. user.Admin = user.bridge.Config.Bridge.Permissions.IsAdmin(user.MXID)
  161. go user.handleMessageLoop()
  162. go user.runMessageRingBuffer()
  163. return user
  164. }
  165. func (user *User) GetManagementRoom() id.RoomID {
  166. if len(user.ManagementRoom) == 0 {
  167. user.mgmtCreateLock.Lock()
  168. defer user.mgmtCreateLock.Unlock()
  169. if len(user.ManagementRoom) > 0 {
  170. return user.ManagementRoom
  171. }
  172. resp, err := user.bridge.Bot.CreateRoom(&mautrix.ReqCreateRoom{
  173. Topic: "WhatsApp bridge notices",
  174. IsDirect: true,
  175. })
  176. if err != nil {
  177. user.log.Errorln("Failed to auto-create management room:", err)
  178. } else {
  179. user.SetManagementRoom(resp.RoomID)
  180. }
  181. }
  182. return user.ManagementRoom
  183. }
  184. func (user *User) SetManagementRoom(roomID id.RoomID) {
  185. existingUser, ok := user.bridge.managementRooms[roomID]
  186. if ok {
  187. existingUser.ManagementRoom = ""
  188. existingUser.Update()
  189. }
  190. user.ManagementRoom = roomID
  191. user.bridge.managementRooms[user.ManagementRoom] = user
  192. user.Update()
  193. }
  194. func (user *User) SetSession(session *whatsapp.Session) {
  195. if session == nil {
  196. user.Session = nil
  197. user.LastConnection = 0
  198. } else if len(session.Wid) > 0 {
  199. user.Session = session
  200. } else {
  201. return
  202. }
  203. user.Update()
  204. }
  205. func (user *User) Connect(evenIfNoSession bool) bool {
  206. user.connLock.Lock()
  207. if user.Conn != nil && user.Conn.IsConnected() {
  208. user.connLock.Unlock()
  209. return true
  210. } else if !evenIfNoSession && user.Session == nil {
  211. user.connLock.Unlock()
  212. return false
  213. }
  214. if user.Conn != nil {
  215. user.Disconnect()
  216. }
  217. user.log.Debugln("Connecting to WhatsApp")
  218. timeout := time.Duration(user.bridge.Config.Bridge.ConnectionTimeout)
  219. if timeout == 0 {
  220. timeout = 20
  221. }
  222. conn, err := whatsapp.NewConnWithOptions(&whatsapp.Options{
  223. Timeout: timeout * time.Second,
  224. LongClientName: user.bridge.Config.WhatsApp.OSName,
  225. ShortClientName: user.bridge.Config.WhatsApp.BrowserName,
  226. ClientVersion: WAVersion,
  227. })
  228. if err != nil {
  229. user.log.Errorln("Failed to connect to WhatsApp:", err)
  230. user.sendMarkdownBridgeAlert("\u26a0 Failed to connect to WhatsApp server. " +
  231. "This indicates a network problem on the bridge server. See bridge logs for more info.")
  232. user.connLock.Unlock()
  233. return false
  234. }
  235. user.Conn = whatsappExt.ExtendConn(conn)
  236. user.log.Debugln("WhatsApp connection successful")
  237. user.Conn.AddHandler(user)
  238. user.connLock.Unlock()
  239. return user.RestoreSession()
  240. }
  241. func (user *User) Disconnect() {
  242. sess, err := user.Conn.Disconnect()
  243. if err != nil && err != whatsapp.ErrNotConnected {
  244. user.log.Warnln("Error disconnecting: %v", err)
  245. }
  246. user.SetSession(&sess)
  247. user.Conn.RemoveHandlers()
  248. user.Conn = nil
  249. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  250. }
  251. func (user *User) RestoreSession() bool {
  252. if user.Session != nil {
  253. sess, err := user.Conn.RestoreWithSession(*user.Session)
  254. if err == whatsapp.ErrAlreadyLoggedIn {
  255. return true
  256. } else if err != nil {
  257. user.log.Errorln("Failed to restore session:", err)
  258. if errors.Is(err, whatsapp.ErrUnpaired) {
  259. user.sendMarkdownBridgeAlert("\u26a0 Failed to connect to WhatsApp: unpaired from phone. " +
  260. "To re-pair your phone, log in again.")
  261. user.Disconnect()
  262. user.removeFromJIDMap()
  263. //user.JID = ""
  264. user.SetSession(nil)
  265. return false
  266. } else {
  267. user.sendMarkdownBridgeAlert("\u26a0 Failed to connect to WhatsApp. Make sure WhatsApp " +
  268. "on your phone is reachable and use `reconnect` to try connecting again.")
  269. }
  270. user.log.Debugln("Disconnecting due to failed session restore...")
  271. _, err := user.Conn.Disconnect()
  272. if err != nil {
  273. user.log.Errorln("Failed to disconnect after failed session restore:", err)
  274. }
  275. return false
  276. }
  277. user.ConnectionErrors = 0
  278. user.SetSession(&sess)
  279. user.log.Debugln("Session restored successfully")
  280. user.PostLogin()
  281. }
  282. return true
  283. }
  284. func (user *User) HasSession() bool {
  285. return user.Session != nil
  286. }
  287. func (user *User) IsConnected() bool {
  288. return user.Conn != nil && user.Conn.IsConnected() && user.Conn.IsLoggedIn()
  289. }
  290. func (user *User) IsLoginInProgress() bool {
  291. return user.Conn != nil && user.Conn.IsLoginInProgress()
  292. }
  293. func (user *User) loginQrChannel(ce *CommandEvent, qrChan <-chan string, eventIDChan chan<- id.EventID) {
  294. var qrEventID id.EventID
  295. for code := range qrChan {
  296. if code == "stop" {
  297. return
  298. }
  299. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  300. if err != nil {
  301. user.log.Errorln("Failed to encode QR code:", err)
  302. ce.Reply("Failed to encode QR code: %v", err)
  303. return
  304. }
  305. bot := user.bridge.AS.BotClient()
  306. resp, err := bot.UploadBytes(qrCode, "image/png")
  307. if err != nil {
  308. user.log.Errorln("Failed to upload QR code:", err)
  309. ce.Reply("Failed to upload QR code: %v", err)
  310. return
  311. }
  312. if qrEventID == "" {
  313. sendResp, err := bot.SendImage(ce.RoomID, code, resp.ContentURI)
  314. if err != nil {
  315. user.log.Errorln("Failed to send QR code to user:", err)
  316. return
  317. }
  318. qrEventID = sendResp.EventID
  319. eventIDChan <- qrEventID
  320. } else {
  321. _, err = bot.SendMessageEvent(ce.RoomID, event.EventMessage, &event.MessageEventContent{
  322. MsgType: event.MsgImage,
  323. Body: code,
  324. URL: resp.ContentURI.CUString(),
  325. NewContent: &event.MessageEventContent{
  326. MsgType: event.MsgImage,
  327. Body: code,
  328. URL: resp.ContentURI.CUString(),
  329. },
  330. RelatesTo: &event.RelatesTo{
  331. Type: event.RelReplace,
  332. EventID: qrEventID,
  333. },
  334. })
  335. if err != nil {
  336. user.log.Errorln("Failed to send edited QR code to user:", err)
  337. }
  338. }
  339. }
  340. }
  341. func (user *User) Login(ce *CommandEvent) {
  342. qrChan := make(chan string, 3)
  343. eventIDChan := make(chan id.EventID, 1)
  344. go user.loginQrChannel(ce, qrChan, eventIDChan)
  345. session, err := user.Conn.LoginWithRetry(qrChan, nil, user.bridge.Config.Bridge.LoginQRRegenCount)
  346. qrChan <- "stop"
  347. if err != nil {
  348. var eventID id.EventID
  349. select {
  350. case eventID = <-eventIDChan:
  351. default:
  352. }
  353. reply := event.MessageEventContent{
  354. MsgType: event.MsgText,
  355. }
  356. if err == whatsapp.ErrAlreadyLoggedIn {
  357. reply.Body = "You're already logged in"
  358. } else if err == whatsapp.ErrLoginInProgress {
  359. reply.Body = "You have a login in progress already."
  360. } else if err == whatsapp.ErrLoginTimedOut {
  361. reply.Body = "QR code scan timed out. Please try again."
  362. } else {
  363. user.log.Warnln("Failed to log in:", err)
  364. reply.Body = fmt.Sprintf("Unknown error while logging in: %v", err)
  365. }
  366. msg := reply
  367. if eventID != "" {
  368. msg.NewContent = &reply
  369. msg.RelatesTo = &event.RelatesTo{
  370. Type: event.RelReplace,
  371. EventID: eventID,
  372. }
  373. }
  374. _, _ = ce.Bot.SendMessageEvent(ce.RoomID, event.EventMessage, &msg)
  375. return
  376. }
  377. // TODO there's a bit of duplication between this and the provisioning API login method
  378. // Also between the two logout methods (commands.go and provisioning.go)
  379. user.ConnectionErrors = 0
  380. user.JID = strings.Replace(user.Conn.Info.Wid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, 1)
  381. user.addToJIDMap()
  382. user.SetSession(&session)
  383. ce.Reply("Successfully logged in, synchronizing chats...")
  384. user.PostLogin()
  385. }
  386. type Chat struct {
  387. Portal *Portal
  388. LastMessageTime uint64
  389. Contact whatsapp.Contact
  390. }
  391. type ChatList []Chat
  392. func (cl ChatList) Len() int {
  393. return len(cl)
  394. }
  395. func (cl ChatList) Less(i, j int) bool {
  396. return cl[i].LastMessageTime > cl[j].LastMessageTime
  397. }
  398. func (cl ChatList) Swap(i, j int) {
  399. cl[i], cl[j] = cl[j], cl[i]
  400. }
  401. func (user *User) PostLogin() {
  402. user.bridge.Metrics.TrackConnectionState(user.JID, true)
  403. user.bridge.Metrics.TrackLoginState(user.JID, true)
  404. user.bridge.Metrics.TrackBufferLength(user.MXID, 0)
  405. user.log.Debugln("Locking processing of incoming messages and starting post-login sync")
  406. // TODO can an old sync still be ongoing when PostLogin is called again?
  407. // TODO 2: can the new sync happen before this happens?
  408. user.chatListReceived = make(chan struct{}, 1)
  409. user.syncPortalsDone = make(chan struct{}, 1)
  410. user.syncWait.Add(1)
  411. user.syncStart <- struct{}{}
  412. go user.intPostLogin(user.Conn)
  413. }
  414. func (user *User) tryAutomaticDoublePuppeting() {
  415. if !user.bridge.Config.CanDoublePuppet(user.MXID) {
  416. return
  417. }
  418. user.log.Debugln("Checking if double puppeting needs to be enabled")
  419. puppet := user.bridge.GetPuppetByJID(user.JID)
  420. if len(puppet.CustomMXID) > 0 {
  421. user.log.Debugln("User already has double-puppeting enabled")
  422. // Custom puppet already enabled
  423. return
  424. }
  425. accessToken, err := puppet.loginWithSharedSecret(user.MXID)
  426. if err != nil {
  427. user.log.Warnln("Failed to login with shared secret:", err)
  428. return
  429. }
  430. err = puppet.SwitchCustomMXID(accessToken, user.MXID)
  431. if err != nil {
  432. puppet.log.Warnln("Failed to switch to auto-logined custom puppet:", err)
  433. return
  434. }
  435. user.log.Infoln("Successfully automatically enabled custom puppet")
  436. }
  437. func (user *User) sendBridgeNotice(formatString string, args ...interface{}) {
  438. notice := fmt.Sprintf(formatString, args...)
  439. _, err := user.bridge.Bot.SendNotice(user.GetManagementRoom(), notice)
  440. if err != nil {
  441. user.log.Warnf("Failed to send bridge notice \"%s\": %v", notice, err)
  442. }
  443. }
  444. func (user *User) sendMarkdownBridgeAlert(formatString string, args ...interface{}) {
  445. notice := fmt.Sprintf(formatString, args...)
  446. content := format.RenderMarkdown(notice, true, false)
  447. _, err := user.bridge.Bot.SendMessageEvent(user.GetManagementRoom(), event.EventMessage, content)
  448. if err != nil {
  449. user.log.Warnf("Failed to send bridge alert \"%s\": %v", notice, err)
  450. }
  451. }
  452. func (user *User) postConnPing(conn *whatsappExt.ExtendedConn) bool {
  453. if user.Conn != conn {
  454. user.log.Warnln("Connection changed before scheduled post-connection ping, canceling ping")
  455. return false
  456. }
  457. user.log.Debugln("Making post-connection ping")
  458. err := conn.AdminTest()
  459. if err != nil {
  460. user.log.Errorfln("Post-connection ping failed: %v. Disconnecting and then reconnecting after a second", err)
  461. sess, disconnectErr := conn.Disconnect()
  462. if disconnectErr != nil {
  463. user.log.Warnln("Error while disconnecting after failed post-connection ping:", disconnectErr)
  464. } else {
  465. user.Session = &sess
  466. }
  467. user.bridge.Metrics.TrackDisconnection(user.MXID)
  468. go func() {
  469. time.Sleep(1 * time.Second)
  470. user.tryReconnect(fmt.Sprintf("Post-connection ping failed: %v", err))
  471. }()
  472. return false
  473. } else {
  474. user.log.Debugln("Post-connection ping OK")
  475. return true
  476. }
  477. }
  478. func (user *User) intPostLogin(conn *whatsappExt.ExtendedConn) {
  479. defer user.syncWait.Done()
  480. user.lastReconnection = time.Now().Unix()
  481. user.createCommunity()
  482. user.tryAutomaticDoublePuppeting()
  483. user.log.Debugln("Waiting for chat list receive confirmation")
  484. select {
  485. case <-user.chatListReceived:
  486. user.log.Debugln("Chat list receive confirmation received in PostLogin")
  487. case <-time.After(time.Duration(user.bridge.Config.Bridge.ChatListWait) * time.Second):
  488. user.log.Warnln("Timed out waiting for chat list to arrive!")
  489. user.postConnPing(conn)
  490. return
  491. }
  492. if !user.postConnPing(conn) {
  493. user.log.Debugln("Post-connection ping failed, unlocking processing of incoming messages.")
  494. return
  495. }
  496. user.log.Debugln("Waiting for portal sync complete confirmation")
  497. select {
  498. case <-user.syncPortalsDone:
  499. user.log.Debugln("Post-connection portal sync complete, unlocking processing of incoming messages.")
  500. // TODO this is too short, maybe a per-portal duration?
  501. case <-time.After(time.Duration(user.bridge.Config.Bridge.PortalSyncWait) * time.Second):
  502. user.log.Warnln("Timed out waiting for portal sync to complete! Unlocking processing of incoming messages.")
  503. }
  504. }
  505. func (user *User) HandleStreamEvent(evt whatsappExt.StreamEvent) {
  506. if evt.Type == whatsappExt.StreamSleep {
  507. if user.lastReconnection+60 > time.Now().Unix() {
  508. user.lastReconnection = 0
  509. user.log.Infoln("Stream went to sleep soon after reconnection, making new post-connection ping in 20 seconds")
  510. conn := user.Conn
  511. go func() {
  512. time.Sleep(20 * time.Second)
  513. // TODO if this happens during the post-login sync, it can get stuck forever
  514. user.postConnPing(conn)
  515. }()
  516. }
  517. } else {
  518. user.log.Infofln("Stream event: %+v", evt)
  519. }
  520. }
  521. func (user *User) HandleChatList(chats []whatsapp.Chat) {
  522. user.log.Infoln("Chat list received")
  523. chatMap := make(map[string]whatsapp.Chat)
  524. for _, chat := range user.Conn.Store.Chats {
  525. chatMap[chat.Jid] = chat
  526. }
  527. for _, chat := range chats {
  528. chatMap[chat.Jid] = chat
  529. }
  530. select {
  531. case user.chatListReceived <- struct{}{}:
  532. default:
  533. }
  534. go user.syncPortals(chatMap, false)
  535. }
  536. func (user *User) syncPortals(chatMap map[string]whatsapp.Chat, createAll bool) {
  537. // TODO use contexts instead of checking if user.Conn is the same?
  538. connAtStart := user.Conn
  539. if chatMap == nil {
  540. chatMap = user.Conn.Store.Chats
  541. }
  542. user.log.Infoln("Reading chat list")
  543. chats := make(ChatList, 0, len(chatMap))
  544. existingKeys := user.GetInCommunityMap()
  545. portalKeys := make([]database.PortalKeyWithMeta, 0, len(chatMap))
  546. for _, chat := range chatMap {
  547. ts, err := strconv.ParseUint(chat.LastMessageTime, 10, 64)
  548. if err != nil {
  549. user.log.Warnfln("Non-integer last message time in %s: %s", chat.Jid, chat.LastMessageTime)
  550. continue
  551. }
  552. portal := user.GetPortalByJID(chat.Jid)
  553. chats = append(chats, Chat{
  554. Portal: portal,
  555. Contact: user.Conn.Store.Contacts[chat.Jid],
  556. LastMessageTime: ts,
  557. })
  558. var inCommunity, ok bool
  559. if inCommunity, ok = existingKeys[portal.Key]; !ok || !inCommunity {
  560. inCommunity = user.addPortalToCommunity(portal)
  561. if portal.IsPrivateChat() {
  562. puppet := user.bridge.GetPuppetByJID(portal.Key.JID)
  563. user.addPuppetToCommunity(puppet)
  564. }
  565. }
  566. portalKeys = append(portalKeys, database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
  567. }
  568. user.log.Infoln("Read chat list, updating user-portal mapping")
  569. err := user.SetPortalKeys(portalKeys)
  570. if err != nil {
  571. user.log.Warnln("Failed to update user-portal mapping:", err)
  572. }
  573. sort.Sort(chats)
  574. limit := user.bridge.Config.Bridge.InitialChatSync
  575. if limit < 0 {
  576. limit = len(chats)
  577. }
  578. if user.Conn != connAtStart {
  579. user.log.Debugln("Connection seems to have changed before sync, cancelling")
  580. return
  581. }
  582. now := uint64(time.Now().Unix())
  583. user.log.Infoln("Syncing portals")
  584. for i, chat := range chats {
  585. if chat.LastMessageTime+user.bridge.Config.Bridge.SyncChatMaxAge < now {
  586. break
  587. }
  588. create := (chat.LastMessageTime >= user.LastConnection && user.LastConnection > 0) || i < limit
  589. if len(chat.Portal.MXID) > 0 || create || createAll {
  590. // Don't sync unless chat meta sync is enabled or portal doesn't exist
  591. if user.bridge.Config.Bridge.ChatMetaSync || len(chat.Portal.MXID) == 0 {
  592. chat.Portal.Sync(user, chat.Contact)
  593. }
  594. err = chat.Portal.BackfillHistory(user, chat.LastMessageTime)
  595. if err != nil {
  596. chat.Portal.log.Errorln("Error backfilling history:", err)
  597. }
  598. }
  599. }
  600. if user.Conn != connAtStart {
  601. user.log.Debugln("Connection seems to have changed during sync, cancelling")
  602. return
  603. }
  604. user.UpdateDirectChats(nil)
  605. user.log.Infoln("Finished syncing portals")
  606. select {
  607. case user.syncPortalsDone <- struct{}{}:
  608. default:
  609. }
  610. }
  611. func (user *User) getDirectChats() map[id.UserID][]id.RoomID {
  612. res := make(map[id.UserID][]id.RoomID)
  613. privateChats := user.bridge.DB.Portal.FindPrivateChats(user.JID)
  614. for _, portal := range privateChats {
  615. if len(portal.MXID) > 0 {
  616. res[user.bridge.FormatPuppetMXID(portal.Key.JID)] = []id.RoomID{portal.MXID}
  617. }
  618. }
  619. return res
  620. }
  621. func (user *User) UpdateDirectChats(chats map[id.UserID][]id.RoomID) {
  622. if !user.bridge.Config.Bridge.SyncDirectChatList {
  623. return
  624. }
  625. puppet := user.bridge.GetPuppetByCustomMXID(user.MXID)
  626. if puppet == nil || puppet.CustomIntent() == nil {
  627. return
  628. }
  629. intent := puppet.CustomIntent()
  630. method := http.MethodPatch
  631. if chats == nil {
  632. chats = user.getDirectChats()
  633. method = http.MethodPut
  634. }
  635. user.log.Debugln("Updating m.direct list on homeserver")
  636. var err error
  637. if user.bridge.Config.Homeserver.Asmux {
  638. urlPath := intent.BuildBaseURL("_matrix", "client", "unstable", "net.maunium.asmux", "dms")
  639. _, err = intent.MakeFullRequest(method, urlPath, http.Header{
  640. "X-Asmux-Auth": {user.bridge.AS.Registration.AppToken},
  641. }, chats, nil)
  642. } else {
  643. existingChats := make(map[id.UserID][]id.RoomID)
  644. err = intent.GetAccountData(event.AccountDataDirectChats.Type, &existingChats)
  645. if err != nil {
  646. user.log.Warnln("Failed to get m.direct list to update it:", err)
  647. return
  648. }
  649. for userID, rooms := range existingChats {
  650. if _, ok := user.bridge.ParsePuppetMXID(userID); !ok {
  651. // This is not a ghost user, include it in the new list
  652. chats[userID] = rooms
  653. } else if _, ok := chats[userID]; !ok && method == http.MethodPatch {
  654. // This is a ghost user, but we're not replacing the whole list, so include it too
  655. chats[userID] = rooms
  656. }
  657. }
  658. err = intent.SetAccountData(event.AccountDataDirectChats.Type, &chats)
  659. }
  660. if err != nil {
  661. user.log.Warnln("Failed to update m.direct list:", err)
  662. }
  663. }
  664. func (user *User) HandleContactList(contacts []whatsapp.Contact) {
  665. contactMap := make(map[string]whatsapp.Contact)
  666. for _, contact := range contacts {
  667. contactMap[contact.Jid] = contact
  668. }
  669. go user.syncPuppets(contactMap)
  670. }
  671. func (user *User) syncPuppets(contacts map[string]whatsapp.Contact) {
  672. if contacts == nil {
  673. contacts = user.Conn.Store.Contacts
  674. }
  675. user.log.Infoln("Syncing puppet info from contacts")
  676. for jid, contact := range contacts {
  677. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  678. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  679. puppet.Sync(user, contact)
  680. }
  681. }
  682. user.log.Infoln("Finished syncing puppet info from contacts")
  683. }
  684. func (user *User) updateLastConnectionIfNecessary() {
  685. if user.LastConnection+60 < uint64(time.Now().Unix()) {
  686. user.UpdateLastConnection()
  687. }
  688. }
  689. func (user *User) HandleError(err error) {
  690. if !errors.Is(err, whatsapp.ErrInvalidWsData) {
  691. user.log.Errorfln("WhatsApp error: %v", err)
  692. }
  693. if closed, ok := err.(*whatsapp.ErrConnectionClosed); ok {
  694. user.bridge.Metrics.TrackDisconnection(user.MXID)
  695. if closed.Code == 1000 && user.cleanDisconnection {
  696. user.cleanDisconnection = false
  697. if !user.bridge.Config.Bridge.AggressiveReconnect {
  698. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  699. user.log.Infoln("Clean disconnection by server")
  700. return
  701. } else {
  702. user.log.Debugln("Clean disconnection by server, but aggressive reconnection is enabled")
  703. }
  704. }
  705. go user.tryReconnect(fmt.Sprintf("Your WhatsApp connection was closed with websocket status code %d", closed.Code))
  706. } else if failed, ok := err.(*whatsapp.ErrConnectionFailed); ok {
  707. user.bridge.Metrics.TrackDisconnection(user.MXID)
  708. user.ConnectionErrors++
  709. go user.tryReconnect(fmt.Sprintf("Your WhatsApp connection failed: %v", failed.Err))
  710. }
  711. // Otherwise unknown error, probably mostly harmless
  712. }
  713. func (user *User) tryReconnect(msg string) {
  714. user.bridge.Metrics.TrackConnectionState(user.JID, false)
  715. if user.ConnectionErrors > user.bridge.Config.Bridge.MaxConnectionAttempts {
  716. user.sendMarkdownBridgeAlert("%s. Use the `reconnect` command to reconnect.", msg)
  717. return
  718. }
  719. if user.bridge.Config.Bridge.ReportConnectionRetry {
  720. user.sendBridgeNotice("%s. Reconnecting...", msg)
  721. // Don't want the same error to be repeated
  722. msg = ""
  723. }
  724. var tries uint
  725. var exponentialBackoff bool
  726. baseDelay := time.Duration(user.bridge.Config.Bridge.ConnectionRetryDelay)
  727. if baseDelay < 0 {
  728. exponentialBackoff = true
  729. baseDelay = -baseDelay + 1
  730. }
  731. delay := baseDelay
  732. conn := user.Conn
  733. takeover := false
  734. for user.ConnectionErrors <= user.bridge.Config.Bridge.MaxConnectionAttempts {
  735. if user.Conn != conn {
  736. user.log.Debugln("Connection was recreated, aborting reconnection attempts")
  737. return
  738. }
  739. err := conn.Restore(takeover)
  740. takeover = true
  741. if err == nil {
  742. user.ConnectionErrors = 0
  743. if user.bridge.Config.Bridge.ReportConnectionRetry {
  744. user.sendBridgeNotice("Reconnected successfully")
  745. }
  746. user.PostLogin()
  747. return
  748. } else if errors.Is(err, whatsapp.ErrBadRequest) {
  749. user.log.Infoln("Got init 400 error when trying to reconnect, resetting connection...")
  750. sess, err := conn.Disconnect()
  751. if err != nil {
  752. user.log.Debugln("Error while disconnecting for connection reset:", err)
  753. }
  754. user.SetSession(&sess)
  755. }
  756. user.log.Errorln("Error while trying to reconnect after disconnection:", err)
  757. tries++
  758. user.ConnectionErrors++
  759. if user.ConnectionErrors <= user.bridge.Config.Bridge.MaxConnectionAttempts {
  760. if exponentialBackoff {
  761. delay = (1 << tries) + baseDelay
  762. }
  763. if user.bridge.Config.Bridge.ReportConnectionRetry {
  764. user.sendBridgeNotice("Reconnection attempt failed: %v. Retrying in %d seconds...", err, delay)
  765. }
  766. time.Sleep(delay * time.Second)
  767. }
  768. }
  769. if user.bridge.Config.Bridge.ReportConnectionRetry {
  770. user.sendMarkdownBridgeAlert("%d reconnection attempts failed. Use the `reconnect` command to try to reconnect manually.", tries)
  771. } else {
  772. user.sendMarkdownBridgeAlert("\u26a0 %s. Additionally, %d reconnection attempts failed. Use the `reconnect` command to try to reconnect.", msg, tries)
  773. }
  774. }
  775. func (user *User) ShouldCallSynchronously() bool {
  776. return true
  777. }
  778. func (user *User) HandleJSONParseError(err error) {
  779. user.log.Errorln("WhatsApp JSON parse error:", err)
  780. }
  781. func (user *User) PortalKey(jid types.WhatsAppID) database.PortalKey {
  782. return database.NewPortalKey(jid, user.JID)
  783. }
  784. func (user *User) GetPortalByJID(jid types.WhatsAppID) *Portal {
  785. return user.bridge.GetPortalByJID(user.PortalKey(jid))
  786. }
  787. func (user *User) runMessageRingBuffer() {
  788. for msg := range user.messageInput {
  789. select {
  790. case user.messageOutput <- msg:
  791. user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput))
  792. default:
  793. dropped := <-user.messageOutput
  794. user.log.Warnln("Buffer is full, dropping message in", dropped.chat)
  795. user.messageOutput <- msg
  796. }
  797. }
  798. }
  799. func (user *User) handleMessageLoop() {
  800. for {
  801. select {
  802. case msg := <-user.messageOutput:
  803. user.bridge.Metrics.TrackBufferLength(user.MXID, len(user.messageOutput))
  804. user.GetPortalByJID(msg.chat).messages <- msg
  805. case <-user.syncStart:
  806. user.log.Debugln("Processing of incoming messages is locked")
  807. user.bridge.Metrics.TrackSyncLock(user.JID, true)
  808. user.syncWait.Wait()
  809. user.bridge.Metrics.TrackSyncLock(user.JID, false)
  810. user.log.Debugln("Processing of incoming messages unlocked")
  811. }
  812. }
  813. }
  814. func (user *User) HandleNewContact(contact whatsapp.Contact) {
  815. user.log.Debugfln("Contact message: %+v", contact)
  816. go func() {
  817. if strings.HasSuffix(contact.Jid, whatsappExt.OldUserSuffix) {
  818. contact.Jid = strings.Replace(contact.Jid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, -1)
  819. }
  820. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  821. puppet.UpdateName(user, contact)
  822. }()
  823. }
  824. func (user *User) HandleBatteryMessage(battery whatsapp.BatteryMessage) {
  825. user.log.Debugfln("Battery message: %+v", battery)
  826. var notice string
  827. if !battery.Plugged && battery.Percentage < 15 && user.batteryWarningsSent < 1 {
  828. notice = fmt.Sprintf("Phone battery low (%d %% remaining)", battery.Percentage)
  829. user.batteryWarningsSent = 1
  830. } else if !battery.Plugged && battery.Percentage < 5 && user.batteryWarningsSent < 2 {
  831. notice = fmt.Sprintf("Phone battery very low (%d %% remaining)", battery.Percentage)
  832. user.batteryWarningsSent = 2
  833. } else if battery.Percentage > 15 || battery.Plugged {
  834. user.batteryWarningsSent = 0
  835. }
  836. if notice != "" {
  837. go user.sendBridgeNotice("%s", notice)
  838. }
  839. }
  840. func (user *User) HandleTextMessage(message whatsapp.TextMessage) {
  841. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  842. }
  843. func (user *User) HandleImageMessage(message whatsapp.ImageMessage) {
  844. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  845. }
  846. func (user *User) HandleStickerMessage(message whatsapp.StickerMessage) {
  847. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  848. }
  849. func (user *User) HandleVideoMessage(message whatsapp.VideoMessage) {
  850. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  851. }
  852. func (user *User) HandleAudioMessage(message whatsapp.AudioMessage) {
  853. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  854. }
  855. func (user *User) HandleDocumentMessage(message whatsapp.DocumentMessage) {
  856. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  857. }
  858. func (user *User) HandleContactMessage(message whatsapp.ContactMessage) {
  859. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  860. }
  861. func (user *User) HandleStubMessage(message whatsapp.StubMessage) {
  862. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  863. }
  864. func (user *User) HandleLocationMessage(message whatsapp.LocationMessage) {
  865. user.messageInput <- PortalMessage{message.Info.RemoteJid, user, message, message.Info.Timestamp}
  866. }
  867. func (user *User) HandleMessageRevoke(message whatsappExt.MessageRevocation) {
  868. user.messageInput <- PortalMessage{message.RemoteJid, user, message, 0}
  869. }
  870. type FakeMessage struct {
  871. Text string
  872. ID string
  873. Alert bool
  874. }
  875. func (user *User) HandleCallInfo(info whatsappExt.CallInfo) {
  876. if info.Data != nil {
  877. return
  878. }
  879. data := FakeMessage{
  880. ID: info.ID,
  881. }
  882. switch info.Type {
  883. case whatsappExt.CallOffer:
  884. if !user.bridge.Config.Bridge.CallNotices.Start {
  885. return
  886. }
  887. data.Text = "Incoming call"
  888. data.Alert = true
  889. case whatsappExt.CallOfferVideo:
  890. if !user.bridge.Config.Bridge.CallNotices.Start {
  891. return
  892. }
  893. data.Text = "Incoming video call"
  894. data.Alert = true
  895. case whatsappExt.CallTerminate:
  896. if !user.bridge.Config.Bridge.CallNotices.End {
  897. return
  898. }
  899. data.Text = "Call ended"
  900. data.ID += "E"
  901. default:
  902. return
  903. }
  904. portal := user.GetPortalByJID(info.From)
  905. if portal != nil {
  906. portal.messages <- PortalMessage{info.From, user, data, 0}
  907. }
  908. }
  909. func (user *User) HandlePresence(info whatsappExt.Presence) {
  910. puppet := user.bridge.GetPuppetByJID(info.SenderJID)
  911. switch info.Status {
  912. case whatsapp.PresenceUnavailable:
  913. _ = puppet.DefaultIntent().SetPresence("offline")
  914. case whatsapp.PresenceAvailable:
  915. if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
  916. portal := user.bridge.GetPortalByMXID(puppet.typingIn)
  917. _, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
  918. puppet.typingIn = ""
  919. puppet.typingAt = 0
  920. } else {
  921. _ = puppet.DefaultIntent().SetPresence("online")
  922. }
  923. case whatsapp.PresenceComposing:
  924. portal := user.GetPortalByJID(info.JID)
  925. if len(puppet.typingIn) > 0 && puppet.typingAt+15 > time.Now().Unix() {
  926. if puppet.typingIn == portal.MXID {
  927. return
  928. }
  929. _, _ = puppet.IntentFor(portal).UserTyping(puppet.typingIn, false, 0)
  930. }
  931. puppet.typingIn = portal.MXID
  932. puppet.typingAt = time.Now().Unix()
  933. _, _ = puppet.IntentFor(portal).UserTyping(portal.MXID, true, 15*1000)
  934. }
  935. }
  936. func (user *User) HandleMsgInfo(info whatsappExt.MsgInfo) {
  937. if (info.Command == whatsappExt.MsgInfoCommandAck || info.Command == whatsappExt.MsgInfoCommandAcks) && info.Acknowledgement == whatsappExt.AckMessageRead {
  938. portal := user.GetPortalByJID(info.ToJID)
  939. if len(portal.MXID) == 0 {
  940. return
  941. }
  942. go func() {
  943. intent := user.bridge.GetPuppetByJID(info.SenderJID).IntentFor(portal)
  944. for _, msgID := range info.IDs {
  945. msg := user.bridge.DB.Message.GetByJID(portal.Key, msgID)
  946. if msg == nil || msg.IsFakeMXID() {
  947. continue
  948. }
  949. err := intent.MarkRead(portal.MXID, msg.MXID)
  950. if err != nil {
  951. user.log.Warnln("Failed to mark message %s as read by %s: %v", msg.MXID, info.SenderJID, err)
  952. }
  953. }
  954. }()
  955. }
  956. }
  957. func (user *User) HandleReceivedMessage(received whatsapp.ReceivedMessage) {
  958. if received.Type == "read" {
  959. user.markSelfRead(received.Jid, received.Index)
  960. } else {
  961. user.log.Debugfln("Unknown received message type: %+v", received)
  962. }
  963. }
  964. func (user *User) HandleReadMessage(read whatsapp.ReadMessage) {
  965. user.log.Debugfln("Received chat read message: %+v", read)
  966. user.markSelfRead(read.Jid, "")
  967. }
  968. func (user *User) markSelfRead(jid, messageID string) {
  969. if strings.HasSuffix(jid, whatsappExt.OldUserSuffix) {
  970. jid = strings.Replace(jid, whatsappExt.OldUserSuffix, whatsappExt.NewUserSuffix, -1)
  971. }
  972. puppet := user.bridge.GetPuppetByJID(user.JID)
  973. if puppet == nil {
  974. return
  975. }
  976. intent := puppet.CustomIntent()
  977. if intent == nil {
  978. return
  979. }
  980. portal := user.GetPortalByJID(jid)
  981. if portal == nil {
  982. return
  983. }
  984. var message *database.Message
  985. if messageID == "" {
  986. message = user.bridge.DB.Message.GetLastInChat(portal.Key)
  987. if message == nil {
  988. return
  989. }
  990. 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)
  991. } else {
  992. message = user.bridge.DB.Message.GetByJID(portal.Key, messageID)
  993. if message == nil || message.IsFakeMXID() {
  994. return
  995. }
  996. user.log.Debugfln("User read message %s/%s in %s/%s in WhatsApp mobile", message.JID, message.MXID, portal.Key.JID, portal.MXID)
  997. }
  998. err := intent.MarkRead(portal.MXID, message.MXID)
  999. if err != nil {
  1000. user.log.Warnfln("Failed to bridge own read receipt in %s: %v", jid, err)
  1001. }
  1002. }
  1003. func (user *User) HandleCommand(cmd whatsappExt.Command) {
  1004. switch cmd.Type {
  1005. case whatsappExt.CommandPicture:
  1006. if strings.HasSuffix(cmd.JID, whatsappExt.NewUserSuffix) {
  1007. puppet := user.bridge.GetPuppetByJID(cmd.JID)
  1008. go puppet.UpdateAvatar(user, cmd.ProfilePicInfo)
  1009. } else if user.bridge.Config.Bridge.ChatMetaSync {
  1010. portal := user.GetPortalByJID(cmd.JID)
  1011. go portal.UpdateAvatar(user, cmd.ProfilePicInfo, true)
  1012. }
  1013. case whatsappExt.CommandDisconnect:
  1014. if cmd.Kind == "replaced" {
  1015. user.cleanDisconnection = true
  1016. go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server because you opened another WhatsApp Web client.\n\n" +
  1017. "Use the `reconnect` command to disconnect the other client and resume bridging.")
  1018. } else {
  1019. user.log.Warnln("Unknown kind of disconnect:", string(cmd.Raw))
  1020. go user.sendMarkdownBridgeAlert("\u26a0 Your WhatsApp connection was closed by the server (reason code: %s).\n\n"+
  1021. "Use the `reconnect` command to reconnect.", cmd.Kind)
  1022. }
  1023. }
  1024. }
  1025. func (user *User) HandleChatUpdate(cmd whatsappExt.ChatUpdate) {
  1026. if cmd.Command != whatsappExt.ChatUpdateCommandAction {
  1027. return
  1028. }
  1029. portal := user.GetPortalByJID(cmd.JID)
  1030. if len(portal.MXID) == 0 {
  1031. if cmd.Data.Action == whatsappExt.ChatActionIntroduce || cmd.Data.Action == whatsappExt.ChatActionCreate {
  1032. go func() {
  1033. err := portal.CreateMatrixRoom(user)
  1034. if err != nil {
  1035. user.log.Errorln("Failed to create portal room after receiving join event:", err)
  1036. }
  1037. }()
  1038. }
  1039. return
  1040. }
  1041. // These don't come down the message history :(
  1042. switch cmd.Data.Action {
  1043. case whatsappExt.ChatActionAddTopic:
  1044. go portal.UpdateTopic(cmd.Data.AddTopic.Topic, cmd.Data.SenderJID, nil,true)
  1045. case whatsappExt.ChatActionRemoveTopic:
  1046. go portal.UpdateTopic("", cmd.Data.SenderJID, nil,true)
  1047. case whatsappExt.ChatActionRemove:
  1048. // We ignore leaving groups in the message history to avoid accidentally leaving rejoined groups,
  1049. // but if we get a real-time command that says we left, it should be safe to bridge it.
  1050. if !user.bridge.Config.Bridge.ChatMetaSync {
  1051. for _, jid := range cmd.Data.UserChange.JIDs {
  1052. if jid == user.JID {
  1053. go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
  1054. break
  1055. }
  1056. }
  1057. }
  1058. }
  1059. if !user.bridge.Config.Bridge.ChatMetaSync {
  1060. // Ignore chat update commands, we're relying on the message history.
  1061. return
  1062. }
  1063. switch cmd.Data.Action {
  1064. case whatsappExt.ChatActionNameChange:
  1065. go portal.UpdateName(cmd.Data.NameChange.Name, cmd.Data.SenderJID, nil, true)
  1066. case whatsappExt.ChatActionPromote:
  1067. go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, true)
  1068. case whatsappExt.ChatActionDemote:
  1069. go portal.ChangeAdminStatus(cmd.Data.UserChange.JIDs, false)
  1070. case whatsappExt.ChatActionAnnounce:
  1071. go portal.RestrictMessageSending(cmd.Data.Announce)
  1072. case whatsappExt.ChatActionRestrict:
  1073. go portal.RestrictMetadataChanges(cmd.Data.Restrict)
  1074. case whatsappExt.ChatActionRemove:
  1075. go portal.HandleWhatsAppKick(nil, cmd.Data.SenderJID, cmd.Data.UserChange.JIDs)
  1076. case whatsappExt.ChatActionAdd:
  1077. go portal.HandleWhatsAppInvite(cmd.Data.SenderJID, nil, cmd.Data.UserChange.JIDs)
  1078. case whatsappExt.ChatActionIntroduce:
  1079. if cmd.Data.SenderJID != "unknown" {
  1080. go portal.Sync(user, whatsapp.Contact{Jid: portal.Key.JID})
  1081. }
  1082. }
  1083. }
  1084. func (user *User) HandleJsonMessage(message string) {
  1085. var msg json.RawMessage
  1086. err := json.Unmarshal([]byte(message), &msg)
  1087. if err != nil {
  1088. return
  1089. }
  1090. user.log.Debugln("JSON message:", message)
  1091. user.updateLastConnectionIfNecessary()
  1092. }
  1093. func (user *User) HandleRawMessage(message *waProto.WebMessageInfo) {
  1094. user.updateLastConnectionIfNecessary()
  1095. }
  1096. func (user *User) HandleUnknownBinaryNode(node *waBinary.Node) {
  1097. user.log.Debugfln("Unknown binary message: %+v", node)
  1098. }
  1099. func (user *User) NeedsRelaybot(portal *Portal) bool {
  1100. return !user.HasSession() || !user.IsInPortal(portal.Key)
  1101. }