commands.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2020 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. "math"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "github.com/Rhymen/go-whatsapp"
  24. "maunium.net/go/maulogger/v2"
  25. "maunium.net/go/mautrix"
  26. "maunium.net/go/mautrix/appservice"
  27. "maunium.net/go/mautrix/event"
  28. "maunium.net/go/mautrix/format"
  29. "maunium.net/go/mautrix/id"
  30. "maunium.net/go/mautrix-whatsapp/database"
  31. "maunium.net/go/mautrix-whatsapp/whatsapp-ext"
  32. )
  33. type CommandHandler struct {
  34. bridge *Bridge
  35. log maulogger.Logger
  36. }
  37. // NewCommandHandler creates a CommandHandler
  38. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  39. return &CommandHandler{
  40. bridge: bridge,
  41. log: bridge.Log.Sub("Command handler"),
  42. }
  43. }
  44. // CommandEvent stores all data which might be used to handle commands
  45. type CommandEvent struct {
  46. Bot *appservice.IntentAPI
  47. Bridge *Bridge
  48. Handler *CommandHandler
  49. RoomID id.RoomID
  50. User *User
  51. Command string
  52. Args []string
  53. }
  54. // Reply sends a reply to command as notice
  55. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  56. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  57. content.MsgType = event.MsgNotice
  58. room := ce.User.ManagementRoom
  59. if len(room) == 0 {
  60. room = ce.RoomID
  61. }
  62. _, err := ce.Bot.SendMessageEvent(room, event.EventMessage, content)
  63. if err != nil {
  64. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  65. }
  66. }
  67. // Handle handles messages to the bridge
  68. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
  69. args := strings.Split(message, " ")
  70. ce := &CommandEvent{
  71. Bot: handler.bridge.Bot,
  72. Bridge: handler.bridge,
  73. Handler: handler,
  74. RoomID: roomID,
  75. User: user,
  76. Command: strings.ToLower(args[0]),
  77. Args: args[1:],
  78. }
  79. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  80. if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
  81. handler.CommandRelaybot(ce)
  82. } else {
  83. handler.CommandMux(ce)
  84. }
  85. }
  86. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  87. switch ce.Command {
  88. case "relaybot":
  89. handler.CommandRelaybot(ce)
  90. case "login":
  91. handler.CommandLogin(ce)
  92. case "logout-matrix":
  93. handler.CommandLogoutMatrix(ce)
  94. case "help":
  95. handler.CommandHelp(ce)
  96. case "reconnect":
  97. handler.CommandReconnect(ce)
  98. case "disconnect":
  99. handler.CommandDisconnect(ce)
  100. case "ping":
  101. handler.CommandPing(ce)
  102. case "delete-connection":
  103. handler.CommandDeleteConnection(ce)
  104. case "delete-session":
  105. handler.CommandDeleteSession(ce)
  106. case "delete-portal":
  107. handler.CommandDeletePortal(ce)
  108. case "delete-all-portals":
  109. handler.CommandDeleteAllPortals(ce)
  110. case "dev-test":
  111. handler.CommandDevTest(ce)
  112. case "set-pl":
  113. handler.CommandSetPowerLevel(ce)
  114. case "logout":
  115. handler.CommandLogout(ce)
  116. case "login-matrix", "sync", "list", "open", "pm":
  117. if !ce.User.HasSession() {
  118. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  119. return
  120. } else if !ce.User.IsConnected() {
  121. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  122. return
  123. }
  124. switch ce.Command {
  125. case "login-matrix":
  126. handler.CommandLoginMatrix(ce)
  127. case "sync":
  128. handler.CommandSync(ce)
  129. case "list":
  130. handler.CommandList(ce)
  131. case "open":
  132. handler.CommandOpen(ce)
  133. case "pm":
  134. handler.CommandPM(ce)
  135. }
  136. default:
  137. ce.Reply("Unknown Command")
  138. }
  139. }
  140. func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
  141. if handler.bridge.Relaybot == nil {
  142. ce.Reply("The relaybot is disabled")
  143. } else if !ce.User.Admin {
  144. ce.Reply("Only admins can manage the relaybot")
  145. } else {
  146. if ce.Command == "relaybot" {
  147. if len(ce.Args) == 0 {
  148. ce.Reply("**Usage:** `relaybot <command>`")
  149. return
  150. }
  151. ce.Command = strings.ToLower(ce.Args[0])
  152. ce.Args = ce.Args[1:]
  153. }
  154. ce.User = handler.bridge.Relaybot
  155. handler.CommandMux(ce)
  156. }
  157. }
  158. func (handler *CommandHandler) CommandDevTest(ce *CommandEvent) {
  159. }
  160. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  161. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  162. if portal == nil {
  163. ce.Reply("Not a portal room")
  164. return
  165. }
  166. var level int
  167. var userID id.UserID
  168. var err error
  169. if len(ce.Args) == 1 {
  170. level, err = strconv.Atoi(ce.Args[0])
  171. if err != nil {
  172. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  173. return
  174. }
  175. userID = ce.User.MXID
  176. } else if len(ce.Args) == 2 {
  177. userID = id.UserID(ce.Args[0])
  178. _, _, err := userID.Parse()
  179. if err != nil {
  180. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  181. return
  182. }
  183. level, err = strconv.Atoi(ce.Args[1])
  184. if err != nil {
  185. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  186. return
  187. }
  188. } else {
  189. ce.Reply("**Usage:** `set-pl [user] <level>`")
  190. return
  191. }
  192. intent := portal.MainIntent()
  193. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  194. if err != nil {
  195. ce.Reply("Failed to set power levels: %v", err)
  196. }
  197. }
  198. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  199. // CommandLogin handles login command
  200. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  201. if !ce.User.Connect(true) {
  202. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  203. return
  204. }
  205. ce.User.Login(ce)
  206. }
  207. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  208. // CommandLogout handles !logout command
  209. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  210. if ce.User.Session == nil {
  211. ce.Reply("You're not logged in.")
  212. return
  213. } else if !ce.User.IsConnected() {
  214. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  215. return
  216. }
  217. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  218. if puppet.CustomMXID != "" {
  219. err := puppet.SwitchCustomMXID("", "")
  220. if err != nil {
  221. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  222. }
  223. }
  224. err := ce.User.Conn.Logout()
  225. if err != nil {
  226. ce.User.log.Warnln("Error while logging out:", err)
  227. ce.Reply("Unknown error while logging out: %v", err)
  228. return
  229. }
  230. _, err = ce.User.Conn.Disconnect()
  231. if err != nil {
  232. ce.User.log.Warnln("Error while disconnecting after logout:", err)
  233. }
  234. ce.User.Conn.RemoveHandlers()
  235. ce.User.Conn = nil
  236. ce.User.removeFromJIDMap()
  237. // TODO this causes a foreign key violation, which should be fixed
  238. //ce.User.JID = ""
  239. ce.User.SetSession(nil)
  240. ce.Reply("Logged out successfully.")
  241. }
  242. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  243. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  244. if ce.User.Session == nil && ce.User.Conn == nil {
  245. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  246. return
  247. }
  248. ce.User.SetSession(nil)
  249. if ce.User.Conn != nil {
  250. _, _ = ce.User.Conn.Disconnect()
  251. ce.User.Conn.RemoveHandlers()
  252. ce.User.Conn = nil
  253. }
  254. ce.Reply("Session information purged")
  255. }
  256. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  257. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  258. if ce.User.Conn == nil {
  259. if ce.User.Session == nil {
  260. ce.Reply("No existing connection and no session. Did you mean `login`?")
  261. } else {
  262. ce.Reply("No existing connection, creating one...")
  263. ce.User.Connect(false)
  264. }
  265. return
  266. }
  267. wasConnected := true
  268. sess, err := ce.User.Conn.Disconnect()
  269. if err == whatsapp.ErrNotConnected {
  270. wasConnected = false
  271. } else if err != nil {
  272. ce.User.log.Warnln("Error while disconnecting:", err)
  273. } else if len(sess.Wid) > 0 {
  274. ce.User.SetSession(&sess)
  275. }
  276. err = ce.User.Conn.Restore()
  277. if err == whatsapp.ErrInvalidSession {
  278. if ce.User.Session != nil {
  279. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  280. var sess whatsapp.Session
  281. sess, err = ce.User.Conn.RestoreWithSession(*ce.User.Session)
  282. if err == nil {
  283. ce.User.SetSession(&sess)
  284. }
  285. } else {
  286. ce.Reply("You are not logged in.")
  287. return
  288. }
  289. } else if err == whatsapp.ErrLoginInProgress {
  290. ce.Reply("A login or reconnection is already in progress.")
  291. return
  292. } else if err == whatsapp.ErrAlreadyLoggedIn {
  293. ce.Reply("You were already connected.")
  294. return
  295. }
  296. if err != nil {
  297. ce.User.log.Warnln("Error while reconnecting:", err)
  298. if err.Error() == "restore session connection timed out" {
  299. ce.Reply("Reconnection timed out. Is WhatsApp on your phone reachable?")
  300. } else {
  301. ce.Reply("Unknown error while reconnecting: %v", err)
  302. }
  303. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  304. sess, err := ce.User.Conn.Disconnect()
  305. if err != nil {
  306. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  307. } else if len(sess.Wid) > 0 {
  308. ce.User.SetSession(&sess)
  309. }
  310. return
  311. }
  312. ce.User.ConnectionErrors = 0
  313. var msg string
  314. if wasConnected {
  315. msg = "Reconnected successfully."
  316. } else {
  317. msg = "Connected successfully."
  318. }
  319. ce.Reply(msg)
  320. ce.User.PostLogin()
  321. }
  322. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  323. if ce.User.Conn == nil {
  324. ce.Reply("You don't have a WhatsApp connection.")
  325. return
  326. }
  327. sess, err := ce.User.Conn.Disconnect()
  328. if err == nil && len(sess.Wid) > 0 {
  329. ce.User.SetSession(&sess)
  330. }
  331. ce.User.Conn.RemoveHandlers()
  332. ce.User.Conn = nil
  333. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  334. }
  335. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  336. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  337. if ce.User.Conn == nil {
  338. ce.Reply("You don't have a WhatsApp connection.")
  339. return
  340. }
  341. sess, err := ce.User.Conn.Disconnect()
  342. if err == whatsapp.ErrNotConnected {
  343. ce.Reply("You were not connected.")
  344. return
  345. } else if err != nil {
  346. ce.User.log.Warnln("Error while disconnecting:", err)
  347. ce.Reply("Unknown error while disconnecting: %v", err)
  348. return
  349. } else if len(sess.Wid) > 0 {
  350. ce.User.SetSession(&sess)
  351. }
  352. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  353. }
  354. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  355. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  356. if ce.User.Session == nil {
  357. if ce.User.IsLoginInProgress() {
  358. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  359. } else {
  360. ce.Reply("You're not logged into WhatsApp.")
  361. }
  362. } else if ce.User.Conn == nil {
  363. ce.Reply("You don't have a WhatsApp connection.")
  364. } else if ok, err := ce.User.Conn.AdminTest(); err != nil {
  365. if ce.User.IsLoginInProgress() {
  366. ce.Reply("Connection not OK: %v, but login in progress", err)
  367. } else {
  368. ce.Reply("Connection not OK: %v", err)
  369. }
  370. } else if !ok {
  371. if ce.User.IsLoginInProgress() {
  372. ce.Reply("Connection not OK, but no error received and login in progress")
  373. } else {
  374. ce.Reply("Connection not OK, but no error received")
  375. }
  376. } else {
  377. ce.Reply("Connection to WhatsApp OK")
  378. }
  379. }
  380. const cmdHelpHelp = `help - Prints this help`
  381. // CommandHelp handles help command
  382. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  383. cmdPrefix := ""
  384. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  385. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  386. }
  387. ce.Reply("* " + strings.Join([]string{
  388. cmdPrefix + cmdHelpHelp,
  389. cmdPrefix + cmdLoginHelp,
  390. cmdPrefix + cmdLogoutHelp,
  391. cmdPrefix + cmdDeleteSessionHelp,
  392. cmdPrefix + cmdReconnectHelp,
  393. cmdPrefix + cmdDisconnectHelp,
  394. cmdPrefix + cmdPingHelp,
  395. cmdPrefix + cmdLoginMatrixHelp,
  396. cmdPrefix + cmdLogoutMatrixHelp,
  397. cmdPrefix + cmdSyncHelp,
  398. cmdPrefix + cmdListHelp,
  399. cmdPrefix + cmdOpenHelp,
  400. cmdPrefix + cmdPMHelp,
  401. }, "\n* "))
  402. }
  403. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  404. // CommandSync handles sync command
  405. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  406. user := ce.User
  407. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  408. ce.Reply("Updating contact and chat list...")
  409. handler.log.Debugln("Importing contacts of", user.MXID)
  410. _, err := user.Conn.Contacts()
  411. if err != nil {
  412. user.log.Errorln("Error updating contacts:", err)
  413. ce.Reply("Failed to sync contact list (see logs for details)")
  414. return
  415. }
  416. handler.log.Debugln("Importing chats of", user.MXID)
  417. _, err = user.Conn.Chats()
  418. if err != nil {
  419. user.log.Errorln("Error updating chats:", err)
  420. ce.Reply("Failed to sync chat list (see logs for details)")
  421. return
  422. }
  423. ce.Reply("Syncing contacts...")
  424. user.syncPuppets(nil)
  425. ce.Reply("Syncing chats...")
  426. user.syncPortals(nil, create)
  427. ce.Reply("Sync complete.")
  428. }
  429. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  430. if !ce.User.Admin {
  431. ce.Reply("Only bridge admins can delete portals")
  432. return
  433. }
  434. portal := ce.Bridge.GetPortalByMXID(ce.RoomID)
  435. if portal == nil {
  436. ce.Reply("You must be in a portal room to use that command")
  437. return
  438. }
  439. portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  440. portal.Delete()
  441. portal.Cleanup(false)
  442. }
  443. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  444. portals := ce.User.GetPortals()
  445. portalsToDelete := make([]*Portal, 0, len(portals))
  446. for _, portal := range portals {
  447. users := portal.GetUserIDs()
  448. if len(users) == 1 && users[0] == ce.User.MXID {
  449. portalsToDelete = append(portalsToDelete, portal)
  450. }
  451. }
  452. leave := func(portal *Portal) {
  453. if len(portal.MXID) > 0 {
  454. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  455. Reason: "Deleting portal",
  456. UserID: ce.User.MXID,
  457. })
  458. }
  459. }
  460. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  461. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  462. intent := customPuppet.CustomIntent()
  463. leave = func(portal *Portal) {
  464. if len(portal.MXID) > 0 {
  465. _, _ = intent.LeaveRoom(portal.MXID)
  466. _, _ = intent.ForgetRoom(portal.MXID)
  467. }
  468. }
  469. }
  470. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  471. for _, portal := range portalsToDelete {
  472. portal.Delete()
  473. leave(portal)
  474. }
  475. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  476. "You may already continue using the bridge. Use `sync` to recreate portals.")
  477. go func() {
  478. for _, portal := range portalsToDelete {
  479. portal.Cleanup(false)
  480. }
  481. ce.Reply("Finished background cleanup of deleted portal rooms.")
  482. }()
  483. }
  484. const cmdListHelp = `list - Get a list of all contacts and groups.`
  485. func formatContacts(contacts bool, skip, max int, input map[string]whatsapp.Contact) (result []string, total int) {
  486. skipped := 0
  487. for jid, contact := range input {
  488. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) != contacts {
  489. continue
  490. }
  491. total++
  492. if skipped < skip || len(result) >= max {
  493. skipped++
  494. continue
  495. }
  496. if contacts {
  497. result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.Jid[:len(contact.Jid)-len(whatsappExt.NewUserSuffix)]))
  498. } else {
  499. result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.Jid))
  500. }
  501. }
  502. sort.Sort(sort.StringSlice(result))
  503. return
  504. }
  505. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  506. if len(ce.Args) == 0 {
  507. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  508. return
  509. }
  510. mode := strings.ToLower(ce.Args[0])
  511. if mode[0] != 'g' && mode[0] != 'c' {
  512. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  513. }
  514. var err error
  515. page := 0
  516. max := 100
  517. if len(ce.Args) > 1 {
  518. page, err = strconv.Atoi(ce.Args[1])
  519. if err != nil || page <= 0 {
  520. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  521. return
  522. }
  523. }
  524. if len(ce.Args) > 2 {
  525. max, err = strconv.Atoi(ce.Args[2])
  526. if err != nil || max <= 0 {
  527. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  528. return
  529. } else if max > 400 {
  530. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  531. }
  532. }
  533. contacts := mode[0] == 'c'
  534. typeName := "Groups"
  535. if contacts {
  536. typeName = "Contacts"
  537. }
  538. result, totalItems := formatContacts(contacts, (page-1)*max, max, ce.User.Conn.Store.Contacts)
  539. pages := int(math.Ceil(float64(totalItems) / float64(max)))
  540. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  541. }
  542. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  543. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  544. if len(ce.Args) == 0 {
  545. ce.Reply("**Usage:** `open <group JID>`")
  546. return
  547. }
  548. user := ce.User
  549. jid := ce.Args[0]
  550. if strings.HasSuffix(jid, whatsappExt.NewUserSuffix) {
  551. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsappExt.NewUserSuffix)])
  552. return
  553. }
  554. contact, ok := user.Conn.Store.Contacts[jid]
  555. if !ok {
  556. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  557. return
  558. }
  559. handler.log.Debugln("Importing", jid, "for", user)
  560. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  561. if len(portal.MXID) > 0 {
  562. portal.Sync(user, contact)
  563. ce.Reply("Portal room synced.")
  564. } else {
  565. portal.Sync(user, contact)
  566. ce.Reply("Portal room created.")
  567. }
  568. _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  569. }
  570. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  571. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  572. if len(ce.Args) == 0 {
  573. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  574. return
  575. }
  576. force := ce.Args[0] == "--force"
  577. if force {
  578. ce.Args = ce.Args[1:]
  579. }
  580. user := ce.User
  581. number := strings.Join(ce.Args, "")
  582. if number[0] == '+' {
  583. number = number[1:]
  584. }
  585. for _, char := range number {
  586. if char < '0' || char > '9' {
  587. ce.Reply("Invalid phone number.")
  588. return
  589. }
  590. }
  591. jid := number + whatsappExt.NewUserSuffix
  592. handler.log.Debugln("Importing", jid, "for", user)
  593. contact, ok := user.Conn.Store.Contacts[jid]
  594. if !ok {
  595. if !force {
  596. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  597. "To create a portal anyway, use `pm --force <number>`.")
  598. return
  599. }
  600. contact = whatsapp.Contact{Jid: jid}
  601. }
  602. puppet := user.bridge.GetPuppetByJID(contact.Jid)
  603. puppet.Sync(user, contact)
  604. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.Jid, user.JID))
  605. if len(portal.MXID) > 0 {
  606. _, err := portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  607. if err != nil {
  608. fmt.Println(err)
  609. } else {
  610. ce.Reply("Existing portal room found, invited you to it.")
  611. }
  612. return
  613. }
  614. err := portal.CreateMatrixRoom(user)
  615. if err != nil {
  616. ce.Reply("Failed to create portal room: %v", err)
  617. return
  618. }
  619. ce.Reply("Created portal room and invited you to it.")
  620. }
  621. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  622. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  623. if len(ce.Args) == 0 {
  624. ce.Reply("**Usage:** `login-matrix <access token>`")
  625. return
  626. }
  627. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  628. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  629. if err != nil {
  630. ce.Reply("Failed to switch puppet: %v", err)
  631. return
  632. }
  633. ce.Reply("Successfully switched puppet")
  634. }
  635. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  636. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  637. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  638. if len(puppet.CustomMXID) == 0 {
  639. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  640. return
  641. }
  642. err := puppet.SwitchCustomMXID("", "")
  643. if err != nil {
  644. ce.Reply("Failed to remove custom puppet: %v", err)
  645. return
  646. }
  647. ce.Reply("Successfully removed custom puppet")
  648. }