commands.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. "fmt"
  19. "strings"
  20. "github.com/Rhymen/go-whatsapp"
  21. "maunium.net/go/maulogger/v2"
  22. "maunium.net/go/mautrix"
  23. "maunium.net/go/mautrix-appservice"
  24. "maunium.net/go/mautrix/format"
  25. "maunium.net/go/mautrix-whatsapp/database"
  26. "maunium.net/go/mautrix-whatsapp/types"
  27. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  28. )
  29. type CommandHandler struct {
  30. bridge *Bridge
  31. log maulogger.Logger
  32. }
  33. // NewCommandHandler creates a CommandHandler
  34. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  35. return &CommandHandler{
  36. bridge: bridge,
  37. log: bridge.Log.Sub("Command handler"),
  38. }
  39. }
  40. // CommandEvent stores all data which might be used to handle commands
  41. type CommandEvent struct {
  42. Bot *appservice.IntentAPI
  43. Bridge *Bridge
  44. Handler *CommandHandler
  45. RoomID types.MatrixRoomID
  46. User *User
  47. Command string
  48. Args []string
  49. }
  50. // Reply sends a reply to command as notice
  51. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  52. content := format.RenderMarkdown(fmt.Sprintf(msg, args...))
  53. content.MsgType = mautrix.MsgNotice
  54. room := ce.User.ManagementRoom
  55. if len(room) == 0 {
  56. room = ce.RoomID
  57. }
  58. _, err := ce.Bot.SendMessageEvent(room, mautrix.EventMessage, content)
  59. if err != nil {
  60. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  61. }
  62. }
  63. // Handle handles messages to the bridge
  64. func (handler *CommandHandler) Handle(roomID types.MatrixRoomID, user *User, message string) {
  65. args := strings.Split(message, " ")
  66. ce := &CommandEvent{
  67. Bot: handler.bridge.Bot,
  68. Bridge: handler.bridge,
  69. Handler: handler,
  70. RoomID: roomID,
  71. User: user,
  72. Command: strings.ToLower(args[0]),
  73. Args: args[1:],
  74. }
  75. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  76. if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
  77. handler.CommandRelaybot(ce)
  78. } else {
  79. handler.CommandMux(ce)
  80. }
  81. }
  82. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  83. switch ce.Command {
  84. case "relaybot":
  85. handler.CommandRelaybot(ce)
  86. case "login":
  87. handler.CommandLogin(ce)
  88. case "logout-matrix":
  89. handler.CommandLogoutMatrix(ce)
  90. case "help":
  91. handler.CommandHelp(ce)
  92. case "reconnect":
  93. handler.CommandReconnect(ce)
  94. case "disconnect":
  95. handler.CommandDisconnect(ce)
  96. case "ping":
  97. handler.CommandPing(ce)
  98. case "delete-connection":
  99. handler.CommandDeleteConnection(ce)
  100. case "delete-session":
  101. handler.CommandDeleteSession(ce)
  102. case "delete-portal":
  103. handler.CommandDeletePortal(ce)
  104. case "delete-all-portals":
  105. handler.CommandDeleteAllPortals(ce)
  106. case "dev-test":
  107. handler.CommandDevTest(ce)
  108. case "login-matrix", "logout", "sync", "list", "open", "pm":
  109. if !ce.User.HasSession() {
  110. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  111. return
  112. } else if !ce.User.IsConnected() {
  113. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  114. return
  115. }
  116. switch ce.Command {
  117. case "login-matrix":
  118. handler.CommandLoginMatrix(ce)
  119. case "logout":
  120. handler.CommandLogout(ce)
  121. case "sync":
  122. handler.CommandSync(ce)
  123. case "list":
  124. handler.CommandList(ce)
  125. case "open":
  126. handler.CommandOpen(ce)
  127. case "pm":
  128. handler.CommandPM(ce)
  129. }
  130. default:
  131. ce.Reply("Unknown Command")
  132. }
  133. }
  134. func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
  135. if handler.bridge.Relaybot == nil {
  136. ce.Reply("The relaybot is disabled")
  137. } else if !ce.User.Admin {
  138. ce.Reply("Only admins can manage the relaybot")
  139. } else {
  140. if ce.Command == "relaybot" {
  141. ce.Command = strings.ToLower(ce.Args[0])
  142. ce.Args = ce.Args[1:]
  143. }
  144. ce.User = handler.bridge.Relaybot
  145. handler.CommandMux(ce)
  146. }
  147. }
  148. func (handler *CommandHandler) CommandDevTest(ce *CommandEvent) {
  149. }
  150. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  151. // CommandLogin handles login command
  152. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  153. if !ce.User.Connect(true) {
  154. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  155. return
  156. }
  157. ce.User.Login(ce)
  158. }
  159. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  160. // CommandLogout handles !logout command
  161. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  162. if ce.User.Session == nil {
  163. ce.Reply("You're not logged in.")
  164. return
  165. }
  166. err := ce.User.Conn.Logout()
  167. if err != nil {
  168. ce.User.log.Warnln("Error while logging out:", err)
  169. ce.Reply("Unknown error while logging out: %v", err)
  170. return
  171. }
  172. _, err = ce.User.Conn.Disconnect()
  173. if err != nil {
  174. ce.User.log.Warnln("Error while disconnecting after logout:", err)
  175. }
  176. ce.User.Conn.RemoveHandlers()
  177. ce.User.Conn = nil
  178. ce.User.SetSession(nil)
  179. ce.Reply("Logged out successfully.")
  180. }
  181. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  182. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  183. if ce.User.Session == nil && ce.User.Conn == nil {
  184. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  185. return
  186. }
  187. ce.User.SetSession(nil)
  188. if ce.User.Conn != nil {
  189. _, _ = ce.User.Conn.Disconnect()
  190. ce.User.Conn.RemoveHandlers()
  191. ce.User.Conn = nil
  192. }
  193. ce.Reply("Session information purged")
  194. }
  195. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  196. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  197. if ce.User.Conn == nil {
  198. if ce.User.Session == nil {
  199. ce.Reply("No existing connection and no session. Did you mean `login`?")
  200. } else {
  201. ce.Reply("No existing connection, creating one...")
  202. ce.User.Connect(false)
  203. }
  204. return
  205. }
  206. err := ce.User.Conn.Restore()
  207. if err == whatsapp.ErrInvalidSession {
  208. if ce.User.Session != nil {
  209. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  210. var sess whatsapp.Session
  211. sess, err = ce.User.Conn.RestoreWithSession(*ce.User.Session)
  212. if err == nil {
  213. ce.User.SetSession(&sess)
  214. }
  215. } else {
  216. ce.Reply("You are not logged in.")
  217. return
  218. }
  219. } else if err == whatsapp.ErrLoginInProgress {
  220. ce.Reply("A login or reconnection is already in progress.")
  221. return
  222. }
  223. if err != nil {
  224. ce.User.log.Warnln("Error while reconnecting:", err)
  225. if err == whatsapp.ErrAlreadyLoggedIn {
  226. ce.Reply("You were already connected.")
  227. } else if err.Error() == "restore session connection timed out" {
  228. ce.Reply("Reconnection timed out. Is WhatsApp on your phone reachable?")
  229. } else {
  230. ce.Reply("Unknown error while reconnecting: %v", err)
  231. }
  232. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  233. sess, err := ce.User.Conn.Disconnect()
  234. if err != nil {
  235. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  236. } else if len(sess.Wid) > 0 {
  237. ce.User.SetSession(&sess)
  238. }
  239. return
  240. }
  241. ce.User.ConnectionErrors = 0
  242. ce.Reply("Reconnected successfully.")
  243. ce.User.PostLogin()
  244. }
  245. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  246. if ce.User.Conn == nil {
  247. ce.Reply("You don't have a WhatsApp connection.")
  248. return
  249. }
  250. sess, err := ce.User.Conn.Disconnect()
  251. if err == nil && len(sess.Wid) > 0 {
  252. ce.User.SetSession(&sess)
  253. }
  254. ce.User.Conn.RemoveHandlers()
  255. ce.User.Conn = nil
  256. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  257. }
  258. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  259. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  260. if ce.User.Conn == nil {
  261. ce.Reply("You don't have a WhatsApp connection.")
  262. return
  263. }
  264. sess, err := ce.User.Conn.Disconnect()
  265. if err == whatsapp.ErrNotConnected {
  266. ce.Reply("You were not connected.")
  267. return
  268. } else if err != nil {
  269. ce.User.log.Warnln("Error while disconnecting:", err)
  270. ce.Reply("Unknown error while disconnecting: %v", err)
  271. return
  272. } else if len(sess.Wid) > 0 {
  273. ce.User.SetSession(&sess)
  274. }
  275. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  276. }
  277. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  278. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  279. if ce.User.Session == nil {
  280. if ce.User.IsLoginInProgress() {
  281. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  282. } else {
  283. ce.Reply("You're not logged into WhatsApp.")
  284. }
  285. } else if ce.User.Conn == nil {
  286. ce.Reply("You don't have a WhatsApp connection.")
  287. } else if ok, err := ce.User.Conn.AdminTest(); err != nil {
  288. if ce.User.IsLoginInProgress() {
  289. ce.Reply("Connection not OK: %v, but login in progress", err)
  290. } else {
  291. ce.Reply("Connection not OK: %v", err)
  292. }
  293. } else if !ok {
  294. if ce.User.IsLoginInProgress() {
  295. ce.Reply("Connection not OK, but no error received and login in progress")
  296. } else {
  297. ce.Reply("Connection not OK, but no error received")
  298. }
  299. } else {
  300. ce.Reply("Connection to WhatsApp OK")
  301. }
  302. }
  303. const cmdHelpHelp = `help - Prints this help`
  304. // CommandHelp handles help command
  305. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  306. cmdPrefix := ""
  307. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  308. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  309. }
  310. ce.Reply("* " + strings.Join([]string{
  311. cmdPrefix + cmdHelpHelp,
  312. cmdPrefix + cmdLoginHelp,
  313. cmdPrefix + cmdLogoutHelp,
  314. cmdPrefix + cmdDeleteSessionHelp,
  315. cmdPrefix + cmdReconnectHelp,
  316. cmdPrefix + cmdDisconnectHelp,
  317. cmdPrefix + cmdPingHelp,
  318. cmdPrefix + cmdLoginMatrixHelp,
  319. cmdPrefix + cmdLogoutMatrixHelp,
  320. cmdPrefix + cmdSyncHelp,
  321. cmdPrefix + cmdListHelp,
  322. cmdPrefix + cmdOpenHelp,
  323. cmdPrefix + cmdPMHelp,
  324. }, "\n* "))
  325. }
  326. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  327. // CommandSync handles sync command
  328. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  329. user := ce.User
  330. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  331. ce.Reply("Updating contact and chat list...")
  332. handler.log.Debugln("Importing contacts of", user.MXID)
  333. _, err := user.Conn.Contacts()
  334. if err != nil {
  335. user.log.Errorln("Error updating contacts:", err)
  336. ce.Reply("Failed to sync contact list (see logs for details)")
  337. return
  338. }
  339. handler.log.Debugln("Importing chats of", user.MXID)
  340. _, err = user.Conn.Chats()
  341. if err != nil {
  342. user.log.Errorln("Error updating chats:", err)
  343. ce.Reply("Failed to sync chat list (see logs for details)")
  344. return
  345. }
  346. ce.Reply("Syncing contacts...")
  347. user.syncPuppets(nil)
  348. ce.Reply("Syncing chats...")
  349. user.syncPortals(nil, create)
  350. ce.Reply("Sync complete.")
  351. }
  352. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  353. if !ce.User.Admin {
  354. ce.Reply("Only bridge admins can delete portals")
  355. return
  356. }
  357. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  358. if portal == nil {
  359. ce.Reply("You must be in a portal room to use that command")
  360. return
  361. }
  362. portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  363. portal.Delete()
  364. portal.Cleanup(false)
  365. }
  366. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  367. portals := ce.User.GetPortals()
  368. portalsToDelete := make([]*Portal, 0, len(portals))
  369. for _, portal := range portals {
  370. users := portal.GetUserIDs()
  371. if len(users) == 1 && users[0] == ce.User.MXID {
  372. portalsToDelete = append(portalsToDelete, portal)
  373. }
  374. }
  375. leave := func(portal *Portal) {
  376. if len(portal.MXID) > 0 {
  377. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  378. Reason: "Deleting portal",
  379. UserID: ce.User.MXID,
  380. })
  381. }
  382. }
  383. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  384. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  385. intent := customPuppet.CustomIntent()
  386. leave = func(portal *Portal) {
  387. if len(portal.MXID) > 0 {
  388. _, _ = intent.LeaveRoom(portal.MXID)
  389. _, _ = intent.ForgetRoom(portal.MXID)
  390. }
  391. }
  392. }
  393. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  394. for _, portal := range portalsToDelete {
  395. portal.Delete()
  396. leave(portal)
  397. }
  398. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  399. "You may already continue using the bridge. Use `sync` to recreate portals.")
  400. go func() {
  401. for _, portal := range portalsToDelete {
  402. portal.Cleanup(false)
  403. }
  404. ce.Reply("Finished background cleanup of deleted portal rooms.")
  405. }()
  406. }
  407. const cmdListHelp = `list - Get a list of all contacts and groups.`
  408. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  409. var contacts strings.Builder
  410. var groups strings.Builder
  411. for jid, contact := range ce.User.Conn.Store.Contacts {
  412. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  413. _, _ = fmt.Fprintf(&contacts, "* %s / %s - `%s`\n", contact.Name, contact.Notify, contact.Jid[:len(contact.Jid)-len(whatsappExt.NewUserSuffix)])
  414. } else {
  415. _, _ = fmt.Fprintf(&groups, "* %s - `%s`\n", contact.Name, contact.Jid)
  416. }
  417. }
  418. ce.Reply("### Contacts\n%s\n\n### Groups\n%s", contacts.String(), groups.String())
  419. }
  420. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  421. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  422. if len(ce.Args) == 0 {
  423. ce.Reply("**Usage:** `open <group JID>`")
  424. return
  425. }
  426. user := ce.User
  427. jid := ce.Args[0]
  428. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  429. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)])
  430. return
  431. }
  432. contact, ok := user.Conn.Store.Contacts[jid]
  433. if !ok {
  434. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  435. return
  436. }
  437. handler.log.Debugln("Importing", jid, "for", user)
  438. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  439. if len(portal.MXID) > 0 {
  440. portal.Sync(user, contact)
  441. ce.Reply("Portal room synced.")
  442. } else {
  443. portal.Sync(user, contact)
  444. ce.Reply("Portal room created.")
  445. }
  446. }
  447. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  448. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  449. if len(ce.Args) == 0 {
  450. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  451. return
  452. }
  453. force := ce.Args[0] == "--force"
  454. if force {
  455. ce.Args = ce.Args[1:]
  456. }
  457. user := ce.User
  458. number := strings.Join(ce.Args, "")
  459. if number[0] == '+' {
  460. number = number[1:]
  461. }
  462. for _, char := range number {
  463. if char < '0' || char > '9' {
  464. ce.Reply("Invalid phone number.")
  465. return
  466. }
  467. }
  468. jid := number + whatsappExt.NewUserSuffix
  469. handler.log.Debugln("Importing", jid, "for", user)
  470. contact, ok := user.Conn.Store.Contacts[jid]
  471. if !ok {
  472. if !force {
  473. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  474. "To create a portal anyway, use `pm --force <number>`.")
  475. return
  476. }
  477. contact = whatsapp.Contact{Jid: jid}
  478. }
  479. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  480. puppet.Sync(user, contact)
  481. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
  482. if len(portal.MXID) > 0 {
  483. _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  484. if err != nil {
  485. fmt.Println(err)
  486. } else {
  487. ce.Reply("Existing portal room found, invited you to it.")
  488. }
  489. return
  490. }
  491. err := portal.CreateMatrixRoom(user)
  492. if err != nil {
  493. ce.Reply("Failed to create portal room: %v", err)
  494. return
  495. }
  496. ce.Reply("Created portal room and invited you to it.")
  497. }
  498. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  499. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  500. if len(ce.Args) == 0 {
  501. ce.Reply("**Usage:** `login-matrix <access token>`")
  502. return
  503. }
  504. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  505. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  506. if err != nil {
  507. ce.Reply("Failed to switch puppet: %v", err)
  508. return
  509. }
  510. ce.Reply("Successfully switched puppet")
  511. }
  512. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  513. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  514. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  515. if len(puppet.CustomMXID) == 0 {
  516. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  517. return
  518. }
  519. err := puppet.SwitchCustomMXID("", "")
  520. if err != nil {
  521. ce.Reply("Failed to remove custom puppet: %v", err)
  522. return
  523. }
  524. ce.Reply("Successfully removed custom puppet")
  525. }