commands.go 21 KB

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