commands.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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) {
  51. content := format.RenderMarkdown(msg)
  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 "logout", "sync", "list", "open", "pm":
  76. if ce.User.Conn == nil {
  77. ce.Reply("You are not logged in.")
  78. ce.Reply("Please use the login command to log into WhatsApp.")
  79. return
  80. }
  81. switch cmd {
  82. case "logout":
  83. handler.CommandLogout(ce)
  84. case "sync":
  85. handler.CommandSync(ce)
  86. case "list":
  87. handler.CommandList(ce)
  88. case "open":
  89. handler.CommandOpen(ce)
  90. case "pm":
  91. handler.CommandPM(ce)
  92. }
  93. default:
  94. ce.Reply("Unknown Command")
  95. }
  96. }
  97. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  98. // CommandLogin handles login command
  99. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  100. if ce.User.Session != nil {
  101. ce.Reply("You're already logged in.")
  102. return
  103. }
  104. ce.User.Connect(true)
  105. ce.User.Login(ce.RoomID)
  106. }
  107. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  108. // CommandLogout handles !logout command
  109. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  110. if ce.User.Session == nil {
  111. ce.Reply("You're not logged in.")
  112. return
  113. }
  114. err := ce.User.Conn.Logout()
  115. if err != nil {
  116. ce.User.log.Warnln("Error while logging out:", err)
  117. ce.Reply("Error while logging out (see logs for details)")
  118. return
  119. }
  120. ce.User.Conn = nil
  121. ce.User.Session = nil
  122. ce.User.Update()
  123. ce.Reply("Logged out successfully.")
  124. }
  125. const cmdHelpHelp = `help - Prints this help`
  126. // CommandHelp handles help command
  127. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  128. cmdPrefix := ""
  129. if ce.User.ManagementRoom != ce.RoomID {
  130. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  131. }
  132. ce.Reply("* " + strings.Join([]string{
  133. cmdPrefix + cmdHelpHelp,
  134. cmdPrefix + cmdLoginHelp,
  135. cmdPrefix + cmdLogoutHelp,
  136. cmdPrefix + cmdSyncHelp,
  137. cmdPrefix + cmdListHelp,
  138. cmdPrefix + cmdOpenHelp,
  139. cmdPrefix + cmdPMHelp,
  140. }, "\n* "))
  141. }
  142. const cmdSyncHelp = `sync [--create] - Synchronize contacts from phone and optionally create portals for group chats.`
  143. // CommandSync handles sync command
  144. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  145. user := ce.User
  146. create := len(ce.Args) > 0 && ce.Args[0] == "--create"
  147. handler.log.Debugln("Importing all contacts of", user)
  148. _, err := user.Conn.Contacts()
  149. if err != nil {
  150. handler.log.Errorln("Error on update of contacts of user", user, ":", err)
  151. return
  152. }
  153. for jid, contact := range user.Conn.Store.Contacts {
  154. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  155. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  156. puppet.Sync(user, contact)
  157. } else {
  158. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(contact.Jid))
  159. if len(portal.MXID) > 0 || create {
  160. portal.Sync(user, contact)
  161. }
  162. }
  163. }
  164. ce.Reply("Imported contacts successfully.")
  165. }
  166. const cmdListHelp = `list - Get a list of all contacts and groups.`
  167. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  168. var contacts strings.Builder
  169. var groups strings.Builder
  170. for jid, contact := range ce.User.Conn.Store.Contacts {
  171. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  172. _, _ = fmt.Fprintf(&contacts, "* %s / %s - `%s`\n", contact.Name, contact.Notify, contact.Jid[:len(contact.Jid)-len(whatsappExt.NewUserSuffix)])
  173. } else {
  174. _, _ = fmt.Fprintf(&groups, "* %s - `%s`\n", contact.Name, contact.Jid)
  175. }
  176. }
  177. ce.Reply(fmt.Sprintf("### Contacts\n%s\n\n### Groups\n%s", contacts.String(), groups.String()))
  178. }
  179. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  180. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  181. if len(ce.Args) == 0 {
  182. ce.Reply("**Usage:** `open <group JID>`")
  183. return
  184. }
  185. user := ce.User
  186. jid := ce.Args[0]
  187. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  188. ce.Reply(fmt.Sprintf("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)]))
  189. return
  190. }
  191. contact, ok := user.Conn.Store.Contacts[jid]
  192. if !ok {
  193. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  194. return
  195. }
  196. handler.log.Debugln("Importing", jid, "for", user)
  197. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  198. if len(portal.MXID) > 0 {
  199. portal.Sync(user, contact)
  200. ce.Reply("Portal room synced.")
  201. } else {
  202. portal.Sync(user, contact)
  203. ce.Reply("Portal room created.")
  204. }
  205. }
  206. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  207. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  208. if len(ce.Args) == 0 {
  209. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  210. return
  211. }
  212. force := ce.Args[0] == "--force"
  213. if force {
  214. ce.Args = ce.Args[1:]
  215. }
  216. user := ce.User
  217. number := strings.Join(ce.Args, "")
  218. if number[0] == '+' {
  219. number = number[1:]
  220. }
  221. for _, char := range number {
  222. if char < '0' || char > '9' {
  223. ce.Reply("Invalid phone number.")
  224. return
  225. }
  226. }
  227. jid := number + whatsappExt.NewUserSuffix
  228. handler.log.Debugln("Importing", jid, "for", user)
  229. contact, ok := user.Conn.Store.Contacts[jid]
  230. if !ok {
  231. if !force {
  232. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  233. "To create a portal anyway, use `pm --force <number>`.")
  234. return
  235. }
  236. contact = whatsapp.Contact{Jid: jid}
  237. }
  238. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  239. puppet.Sync(user, contact)
  240. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
  241. if len(portal.MXID) > 0 {
  242. _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  243. if err != nil {
  244. fmt.Println(err)
  245. } else {
  246. ce.Reply("Existing portal room found, invited you to it.")
  247. }
  248. return
  249. }
  250. err := portal.CreateMatrixRoom(user)
  251. if err != nil {
  252. ce.Reply(fmt.Sprintf("Failed to create portal room: %v", err))
  253. return
  254. }
  255. ce.Reply("Created portal room and invited you to it.")
  256. }