commands.go 12 KB

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