commands.go 22 KB

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