commands.go 15 KB

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