commands.go 15 KB

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