commands.go 22 KB

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