commands.go 22 KB

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