commands.go 21 KB

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