commands.go 25 KB

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