commands.go 22 KB

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