commands.go 24 KB

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