commands.go 11 KB

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