commands.go 12 KB

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