commands.go 17 KB

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