commands.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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. "context"
  19. "errors"
  20. "fmt"
  21. "math"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "github.com/Rhymen/go-whatsapp"
  26. "maunium.net/go/maulogger/v2"
  27. "maunium.net/go/mautrix"
  28. "maunium.net/go/mautrix/appservice"
  29. "maunium.net/go/mautrix/event"
  30. "maunium.net/go/mautrix/format"
  31. "maunium.net/go/mautrix/id"
  32. "maunium.net/go/mautrix-whatsapp/database"
  33. )
  34. type CommandHandler struct {
  35. bridge *Bridge
  36. log maulogger.Logger
  37. }
  38. // NewCommandHandler creates a CommandHandler
  39. func NewCommandHandler(bridge *Bridge) *CommandHandler {
  40. return &CommandHandler{
  41. bridge: bridge,
  42. log: bridge.Log.Sub("Command handler"),
  43. }
  44. }
  45. // CommandEvent stores all data which might be used to handle commands
  46. type CommandEvent struct {
  47. Bot *appservice.IntentAPI
  48. Bridge *Bridge
  49. Portal *Portal
  50. Handler *CommandHandler
  51. RoomID id.RoomID
  52. User *User
  53. Command string
  54. Args []string
  55. }
  56. // Reply sends a reply to command as notice
  57. func (ce *CommandEvent) Reply(msg string, args ...interface{}) {
  58. content := format.RenderMarkdown(fmt.Sprintf(msg, args...), true, false)
  59. content.MsgType = event.MsgNotice
  60. intent := ce.Bot
  61. if ce.Portal != nil && ce.Portal.IsPrivateChat() {
  62. intent = ce.Portal.MainIntent()
  63. }
  64. _, err := intent.SendMessageEvent(ce.RoomID, event.EventMessage, content)
  65. if err != nil {
  66. ce.Handler.log.Warnfln("Failed to reply to command from %s: %v", ce.User.MXID, err)
  67. }
  68. }
  69. // Handle handles messages to the bridge
  70. func (handler *CommandHandler) Handle(roomID id.RoomID, user *User, message string) {
  71. args := strings.Fields(message)
  72. if len(args) == 0 {
  73. args = []string{"unknown-command"}
  74. }
  75. ce := &CommandEvent{
  76. Bot: handler.bridge.Bot,
  77. Bridge: handler.bridge,
  78. Portal: handler.bridge.GetPortalByMXID(roomID),
  79. Handler: handler,
  80. RoomID: roomID,
  81. User: user,
  82. Command: strings.ToLower(args[0]),
  83. Args: args[1:],
  84. }
  85. handler.log.Debugfln("%s sent '%s' in %s", user.MXID, message, roomID)
  86. if roomID == handler.bridge.Config.Bridge.Relaybot.ManagementRoom {
  87. handler.CommandRelaybot(ce)
  88. } else {
  89. handler.CommandMux(ce)
  90. }
  91. }
  92. func (handler *CommandHandler) CommandMux(ce *CommandEvent) {
  93. switch ce.Command {
  94. case "relaybot":
  95. handler.CommandRelaybot(ce)
  96. case "login":
  97. handler.CommandLogin(ce)
  98. case "logout-matrix":
  99. handler.CommandLogoutMatrix(ce)
  100. case "help":
  101. handler.CommandHelp(ce)
  102. case "version":
  103. handler.CommandVersion(ce)
  104. case "reconnect", "connect":
  105. handler.CommandReconnect(ce)
  106. case "disconnect":
  107. handler.CommandDisconnect(ce)
  108. case "ping":
  109. handler.CommandPing(ce)
  110. case "delete-connection":
  111. handler.CommandDeleteConnection(ce)
  112. case "delete-session":
  113. handler.CommandDeleteSession(ce)
  114. case "delete-portal":
  115. handler.CommandDeletePortal(ce)
  116. case "delete-all-portals":
  117. handler.CommandDeleteAllPortals(ce)
  118. case "discard-megolm-session", "discard-session":
  119. handler.CommandDiscardMegolmSession(ce)
  120. case "dev-test":
  121. handler.CommandDevTest(ce)
  122. case "set-pl":
  123. handler.CommandSetPowerLevel(ce)
  124. case "logout":
  125. handler.CommandLogout(ce)
  126. case "toggle":
  127. handler.CommandToggle(ce)
  128. case "login-matrix", "sync", "list", "open", "pm", "invite-link", "join", "create":
  129. if !ce.User.HasSession() {
  130. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  131. return
  132. } else if !ce.User.IsConnected() {
  133. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  134. return
  135. }
  136. switch ce.Command {
  137. case "login-matrix":
  138. handler.CommandLoginMatrix(ce)
  139. case "sync":
  140. handler.CommandSync(ce)
  141. case "list":
  142. handler.CommandList(ce)
  143. case "open":
  144. handler.CommandOpen(ce)
  145. case "pm":
  146. handler.CommandPM(ce)
  147. case "invite-link":
  148. handler.CommandInviteLink(ce)
  149. case "join":
  150. handler.CommandJoin(ce)
  151. case "create":
  152. handler.CommandCreate(ce)
  153. }
  154. default:
  155. ce.Reply("Unknown command, use the `help` command for help.")
  156. }
  157. }
  158. func (handler *CommandHandler) CommandDiscardMegolmSession(ce *CommandEvent) {
  159. if handler.bridge.Crypto == nil {
  160. ce.Reply("This bridge instance doesn't have end-to-bridge encryption enabled")
  161. } else if !ce.User.Admin {
  162. ce.Reply("Only the bridge admin can reset Megolm sessions")
  163. } else {
  164. handler.bridge.Crypto.ResetSession(ce.RoomID)
  165. ce.Reply("Successfully reset Megolm session in this room. New decryption keys will be shared the next time a message is sent from WhatsApp.")
  166. }
  167. }
  168. func (handler *CommandHandler) CommandRelaybot(ce *CommandEvent) {
  169. if handler.bridge.Relaybot == nil {
  170. ce.Reply("The relaybot is disabled")
  171. } else if !ce.User.Admin {
  172. ce.Reply("Only admins can manage the relaybot")
  173. } else {
  174. if ce.Command == "relaybot" {
  175. if len(ce.Args) == 0 {
  176. ce.Reply("**Usage:** `relaybot <command>`")
  177. return
  178. }
  179. ce.Command = strings.ToLower(ce.Args[0])
  180. ce.Args = ce.Args[1:]
  181. }
  182. ce.User = handler.bridge.Relaybot
  183. handler.CommandMux(ce)
  184. }
  185. }
  186. func (handler *CommandHandler) CommandDevTest(_ *CommandEvent) {
  187. }
  188. const cmdVersionHelp = `version - View the bridge version`
  189. func (handler *CommandHandler) CommandVersion(ce *CommandEvent) {
  190. version := fmt.Sprintf("v%s.unknown", Version)
  191. if Tag == Version {
  192. version = fmt.Sprintf("[v%s](%s/releases/v%s) (%s)", Version, URL, Tag, BuildTime)
  193. } else if len(Commit) > 8 {
  194. version = fmt.Sprintf("v%s.[%s](%s/commit/%s) (%s)", Version, Commit[:8], URL, Commit, BuildTime)
  195. }
  196. ce.Reply(fmt.Sprintf("[%s](%s) %s", Name, URL, version))
  197. }
  198. const cmdInviteLinkHelp = `invite-link - Get an invite link to the current group chat.`
  199. func (handler *CommandHandler) CommandInviteLink(ce *CommandEvent) {
  200. if ce.Portal == nil {
  201. ce.Reply("Not a portal room")
  202. return
  203. } else if ce.Portal.IsPrivateChat() {
  204. ce.Reply("Can't get invite link to private chat")
  205. return
  206. }
  207. link, err := ce.User.Conn.GroupInviteLink(ce.Portal.Key.JID)
  208. if err != nil {
  209. ce.Reply("Failed to get invite link: %v", err)
  210. return
  211. }
  212. ce.Reply("%s%s", inviteLinkPrefix, link)
  213. }
  214. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  215. const inviteLinkPrefix = "https://chat.whatsapp.com/"
  216. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  217. if len(ce.Args) == 0 {
  218. ce.Reply("**Usage:** `join <invite link>`")
  219. return
  220. } else if len(ce.Args[0]) <= len(inviteLinkPrefix) || ce.Args[0][:len(inviteLinkPrefix)] != inviteLinkPrefix {
  221. ce.Reply("That doesn't look like a WhatsApp invite link")
  222. return
  223. }
  224. jid, err := ce.User.Conn.GroupAcceptInviteCode(ce.Args[0][len(inviteLinkPrefix):])
  225. if err != nil {
  226. ce.Reply("Failed to join group: %v", err)
  227. return
  228. }
  229. handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  230. portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  231. if len(portal.MXID) > 0 {
  232. portal.Sync(ce.User, whatsapp.Contact{JID: portal.Key.JID})
  233. ce.Reply("Successfully joined group \"%s\" and synced portal room: [%s](https://matrix.to/#/%s)", portal.Name, portal.Name, portal.MXID)
  234. } else {
  235. err = portal.CreateMatrixRoom(ce.User)
  236. if err != nil {
  237. ce.Reply("Failed to create portal room: %v", err)
  238. return
  239. }
  240. ce.Reply("Successfully joined group \"%s\" and created portal room: [%s](https://matrix.to/#/%s)", portal.Name, portal.Name, portal.MXID)
  241. }
  242. }
  243. const cmdCreateHelp = `create - Create a group chat.`
  244. func (handler *CommandHandler) CommandCreate(ce *CommandEvent) {
  245. if ce.Portal != nil {
  246. ce.Reply("This is already a portal room")
  247. return
  248. }
  249. members, err := ce.Bot.JoinedMembers(ce.RoomID)
  250. if err != nil {
  251. ce.Reply("Failed to get room members: %v", err)
  252. return
  253. }
  254. var roomNameEvent event.RoomNameEventContent
  255. err = ce.Bot.StateEvent(ce.RoomID, event.StateRoomName, "", &roomNameEvent)
  256. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  257. ce.Reply("Failed to get room name")
  258. return
  259. } else if len(roomNameEvent.Name) == 0 {
  260. ce.Reply("Please set a name for the room first")
  261. return
  262. }
  263. var encryptionEvent event.EncryptionEventContent
  264. err = ce.Bot.StateEvent(ce.RoomID, event.StateEncryption, "", &encryptionEvent)
  265. if err != nil && !errors.Is(err, mautrix.MNotFound) {
  266. ce.Reply("Failed to get room encryption status")
  267. return
  268. }
  269. participants := []string{ce.User.JID}
  270. for userID := range members.Joined {
  271. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  272. if ok && jid != ce.User.JID {
  273. participants = append(participants, jid)
  274. }
  275. }
  276. resp, err := ce.User.Conn.CreateGroup(roomNameEvent.Name, participants)
  277. if err != nil {
  278. ce.Reply("Failed to create group: %v", err)
  279. return
  280. }
  281. portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(resp.GroupID))
  282. portal.roomCreateLock.Lock()
  283. defer portal.roomCreateLock.Unlock()
  284. if len(portal.MXID) != 0 {
  285. portal.log.Warnln("Detected race condition in room creation")
  286. // TODO race condition, clean up the old room
  287. }
  288. portal.MXID = ce.RoomID
  289. portal.Name = roomNameEvent.Name
  290. portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  291. if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  292. _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  293. if err != nil {
  294. portal.log.Warnln("Failed to enable e2be:", err)
  295. }
  296. portal.Encrypted = true
  297. }
  298. portal.Update()
  299. portal.UpdateBridgeInfo()
  300. ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  301. inCommunity := ce.User.addPortalToCommunity(portal)
  302. ce.User.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
  303. }
  304. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  305. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  306. if ce.Portal == nil {
  307. ce.Reply("Not a portal room")
  308. return
  309. }
  310. var level int
  311. var userID id.UserID
  312. var err error
  313. if len(ce.Args) == 1 {
  314. level, err = strconv.Atoi(ce.Args[0])
  315. if err != nil {
  316. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  317. return
  318. }
  319. userID = ce.User.MXID
  320. } else if len(ce.Args) == 2 {
  321. userID = id.UserID(ce.Args[0])
  322. _, _, err := userID.Parse()
  323. if err != nil {
  324. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  325. return
  326. }
  327. level, err = strconv.Atoi(ce.Args[1])
  328. if err != nil {
  329. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  330. return
  331. }
  332. } else {
  333. ce.Reply("**Usage:** `set-pl [user] <level>`")
  334. return
  335. }
  336. intent := ce.Portal.MainIntent()
  337. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  338. if err != nil {
  339. ce.Reply("Failed to set power levels: %v", err)
  340. }
  341. }
  342. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  343. // CommandLogin handles login command
  344. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  345. if !ce.User.Connect(true) {
  346. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  347. return
  348. }
  349. ce.User.Login(ce)
  350. }
  351. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  352. // CommandLogout handles !logout command
  353. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  354. if ce.User.Session == nil {
  355. ce.Reply("You're not logged in.")
  356. return
  357. } else if !ce.User.IsConnected() {
  358. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  359. return
  360. }
  361. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  362. if puppet.CustomMXID != "" {
  363. err := puppet.SwitchCustomMXID("", "")
  364. if err != nil {
  365. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  366. }
  367. }
  368. err := ce.User.Conn.Logout()
  369. if err != nil {
  370. ce.User.log.Warnln("Error while logging out:", err)
  371. ce.Reply("Unknown error while logging out: %v", err)
  372. return
  373. }
  374. ce.User.removeFromJIDMap()
  375. // TODO this causes a foreign key violation, which should be fixed
  376. //ce.User.JID = ""
  377. ce.User.SetSession(nil)
  378. ce.User.DeleteConnection()
  379. ce.Reply("Logged out successfully.")
  380. }
  381. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence, read receipts, or all`
  382. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  383. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  384. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  385. return
  386. }
  387. if ce.User.Session == nil {
  388. ce.Reply("You're not logged in.")
  389. return
  390. }
  391. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  392. if customPuppet == nil {
  393. ce.Reply("You're not logged in with your Matrix account.")
  394. return
  395. }
  396. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  397. customPuppet.EnablePresence = !customPuppet.EnablePresence
  398. var newPresence whatsapp.Presence
  399. if customPuppet.EnablePresence {
  400. newPresence = whatsapp.PresenceAvailable
  401. ce.Reply("Enabled presence bridging")
  402. } else {
  403. newPresence = whatsapp.PresenceUnavailable
  404. ce.Reply("Disabled presence bridging")
  405. }
  406. if ce.User.IsConnected() {
  407. _, err := ce.User.Conn.Presence("", newPresence)
  408. if err != nil {
  409. ce.User.log.Warnln("Failed to set presence:", err)
  410. }
  411. }
  412. } else if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  413. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  414. if customPuppet.EnableReceipts {
  415. ce.Reply("Enabled read receipt bridging")
  416. } else {
  417. ce.Reply("Disabled read receipt bridging")
  418. }
  419. }
  420. customPuppet.Update()
  421. }
  422. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  423. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  424. if ce.User.Session == nil && ce.User.Conn == nil {
  425. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  426. return
  427. }
  428. //ce.User.JID = ""
  429. ce.User.removeFromJIDMap()
  430. ce.User.SetSession(nil)
  431. ce.User.DeleteConnection()
  432. ce.Reply("Session information purged")
  433. }
  434. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  435. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  436. if ce.User.Conn == nil {
  437. if ce.User.Session == nil {
  438. ce.Reply("No existing connection and no session. Did you mean `login`?")
  439. } else {
  440. ce.Reply("No existing connection, creating one...")
  441. ce.User.Connect(false)
  442. }
  443. return
  444. }
  445. wasConnected := true
  446. err := ce.User.Conn.Disconnect()
  447. if err == whatsapp.ErrNotConnected {
  448. wasConnected = false
  449. } else if err != nil {
  450. ce.User.log.Warnln("Error while disconnecting:", err)
  451. }
  452. ctx := context.Background()
  453. err = ce.User.Conn.Restore(true, ctx)
  454. if err == whatsapp.ErrInvalidSession {
  455. if ce.User.Session != nil {
  456. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  457. ce.User.Conn.SetSession(*ce.User.Session)
  458. err = ce.User.Conn.Restore(true, ctx)
  459. } else {
  460. ce.Reply("You are not logged in.")
  461. return
  462. }
  463. } else if err == whatsapp.ErrLoginInProgress {
  464. ce.Reply("A login or reconnection is already in progress.")
  465. return
  466. } else if err == whatsapp.ErrAlreadyLoggedIn {
  467. ce.Reply("You were already connected.")
  468. return
  469. }
  470. if err != nil {
  471. ce.User.log.Warnln("Error while reconnecting:", err)
  472. ce.Reply("Unknown error while reconnecting: %v", err)
  473. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  474. err = ce.User.Conn.Disconnect()
  475. if err != nil {
  476. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  477. }
  478. return
  479. }
  480. ce.User.ConnectionErrors = 0
  481. var msg string
  482. if wasConnected {
  483. msg = "Reconnected successfully."
  484. } else {
  485. msg = "Connected successfully."
  486. }
  487. ce.Reply(msg)
  488. ce.User.PostLogin()
  489. }
  490. const cmdDeleteConnectionHelp = `delete-connection - Disconnect ignoring errors and delete internal connection state.`
  491. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  492. if ce.User.Conn == nil {
  493. ce.Reply("You don't have a WhatsApp connection.")
  494. return
  495. }
  496. ce.User.DeleteConnection()
  497. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  498. }
  499. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  500. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  501. if ce.User.Conn == nil {
  502. ce.Reply("You don't have a WhatsApp connection.")
  503. return
  504. }
  505. err := ce.User.Conn.Disconnect()
  506. if err == whatsapp.ErrNotConnected {
  507. ce.Reply("You were not connected.")
  508. return
  509. } else if err != nil {
  510. ce.User.log.Warnln("Error while disconnecting:", err)
  511. ce.Reply("Unknown error while disconnecting: %v", err)
  512. return
  513. }
  514. ce.User.bridge.Metrics.TrackConnectionState(ce.User.JID, false)
  515. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  516. }
  517. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  518. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  519. if ce.User.Session == nil {
  520. if ce.User.IsLoginInProgress() {
  521. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  522. } else {
  523. ce.Reply("You're not logged into WhatsApp.")
  524. }
  525. } else if ce.User.Conn == nil {
  526. ce.Reply("You don't have a WhatsApp connection.")
  527. } else if err := ce.User.Conn.AdminTest(); err != nil {
  528. if ce.User.IsLoginInProgress() {
  529. ce.Reply("Connection not OK: %v, but login in progress", err)
  530. } else {
  531. ce.Reply("Connection not OK: %v", err)
  532. }
  533. } else {
  534. ce.Reply("Connection to WhatsApp OK")
  535. }
  536. }
  537. const cmdHelpHelp = `help - Prints this help`
  538. // CommandHelp handles help command
  539. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  540. cmdPrefix := ""
  541. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  542. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  543. }
  544. ce.Reply("* " + strings.Join([]string{
  545. cmdPrefix + cmdHelpHelp,
  546. cmdPrefix + cmdLoginHelp,
  547. cmdPrefix + cmdLogoutHelp,
  548. cmdPrefix + cmdDeleteSessionHelp,
  549. cmdPrefix + cmdReconnectHelp,
  550. cmdPrefix + cmdDisconnectHelp,
  551. cmdPrefix + cmdDeleteConnectionHelp,
  552. cmdPrefix + cmdPingHelp,
  553. cmdPrefix + cmdLoginMatrixHelp,
  554. cmdPrefix + cmdLogoutMatrixHelp,
  555. cmdPrefix + cmdToggleHelp,
  556. cmdPrefix + cmdSyncHelp,
  557. cmdPrefix + cmdListHelp,
  558. cmdPrefix + cmdOpenHelp,
  559. cmdPrefix + cmdPMHelp,
  560. cmdPrefix + cmdInviteLinkHelp,
  561. cmdPrefix + cmdJoinHelp,
  562. cmdPrefix + cmdCreateHelp,
  563. cmdPrefix + cmdSetPowerLevelHelp,
  564. cmdPrefix + cmdDeletePortalHelp,
  565. cmdPrefix + cmdDeleteAllPortalsHelp,
  566. }, "\n* "))
  567. }
  568. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  569. // CommandSync handles sync command
  570. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  571. user := ce.User
  572. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  573. ce.Reply("Updating contact and chat list...")
  574. handler.log.Debugln("Importing contacts of", user.MXID)
  575. _, err := user.Conn.Contacts()
  576. if err != nil {
  577. user.log.Errorln("Error updating contacts:", err)
  578. ce.Reply("Failed to sync contact list (see logs for details)")
  579. return
  580. }
  581. handler.log.Debugln("Importing chats of", user.MXID)
  582. _, err = user.Conn.Chats()
  583. if err != nil {
  584. user.log.Errorln("Error updating chats:", err)
  585. ce.Reply("Failed to sync chat list (see logs for details)")
  586. return
  587. }
  588. ce.Reply("Syncing contacts...")
  589. user.syncPuppets(nil)
  590. ce.Reply("Syncing chats...")
  591. user.syncPortals(nil, create)
  592. ce.Reply("Sync complete.")
  593. }
  594. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  595. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  596. if ce.Portal == nil {
  597. ce.Reply("You must be in a portal room to use that command")
  598. return
  599. }
  600. if !ce.User.Admin {
  601. users := ce.Portal.GetUserIDs()
  602. if len(users) > 1 || (len(users) == 1 && users[0] != ce.User.MXID) {
  603. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  604. return
  605. }
  606. }
  607. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  608. ce.Portal.Delete()
  609. ce.Portal.Cleanup(false)
  610. }
  611. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all your portals that aren't used by any other user.'`
  612. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  613. portals := ce.User.GetPortals()
  614. portalsToDelete := make([]*Portal, 0, len(portals))
  615. for _, portal := range portals {
  616. users := portal.GetUserIDs()
  617. if len(users) == 1 && users[0] == ce.User.MXID {
  618. portalsToDelete = append(portalsToDelete, portal)
  619. }
  620. }
  621. leave := func(portal *Portal) {
  622. if len(portal.MXID) > 0 {
  623. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  624. Reason: "Deleting portal",
  625. UserID: ce.User.MXID,
  626. })
  627. }
  628. }
  629. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  630. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  631. intent := customPuppet.CustomIntent()
  632. leave = func(portal *Portal) {
  633. if len(portal.MXID) > 0 {
  634. _, _ = intent.LeaveRoom(portal.MXID)
  635. _, _ = intent.ForgetRoom(portal.MXID)
  636. }
  637. }
  638. }
  639. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  640. for _, portal := range portalsToDelete {
  641. portal.Delete()
  642. leave(portal)
  643. }
  644. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  645. "You may already continue using the bridge. Use `sync` to recreate portals.")
  646. go func() {
  647. for _, portal := range portalsToDelete {
  648. portal.Cleanup(false)
  649. }
  650. ce.Reply("Finished background cleanup of deleted portal rooms.")
  651. }()
  652. }
  653. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  654. func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  655. for jid, contact := range input {
  656. if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  657. continue
  658. }
  659. if contacts {
  660. result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  661. } else {
  662. result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  663. }
  664. }
  665. sort.Sort(sort.StringSlice(result))
  666. return
  667. }
  668. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  669. if len(ce.Args) == 0 {
  670. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  671. return
  672. }
  673. mode := strings.ToLower(ce.Args[0])
  674. if mode[0] != 'g' && mode[0] != 'c' {
  675. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  676. return
  677. }
  678. var err error
  679. page := 1
  680. max := 100
  681. if len(ce.Args) > 1 {
  682. page, err = strconv.Atoi(ce.Args[1])
  683. if err != nil || page <= 0 {
  684. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  685. return
  686. }
  687. }
  688. if len(ce.Args) > 2 {
  689. max, err = strconv.Atoi(ce.Args[2])
  690. if err != nil || max <= 0 {
  691. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  692. return
  693. } else if max > 400 {
  694. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  695. }
  696. }
  697. contacts := mode[0] == 'c'
  698. typeName := "Groups"
  699. if contacts {
  700. typeName = "Contacts"
  701. }
  702. result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  703. if len(result) == 0 {
  704. ce.Reply("No %s found", strings.ToLower(typeName))
  705. return
  706. }
  707. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  708. if (page-1)*max >= len(result) {
  709. if pages == 1 {
  710. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  711. } else {
  712. ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  713. }
  714. return
  715. }
  716. lastIndex := page * max
  717. if lastIndex > len(result) {
  718. lastIndex = len(result)
  719. }
  720. result = result[(page-1)*max : lastIndex]
  721. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  722. }
  723. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  724. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  725. if len(ce.Args) == 0 {
  726. ce.Reply("**Usage:** `open <group JID>`")
  727. return
  728. }
  729. user := ce.User
  730. jid := ce.Args[0]
  731. if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  732. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  733. return
  734. }
  735. contact, ok := user.Conn.Store.Contacts[jid]
  736. if !ok {
  737. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  738. return
  739. }
  740. handler.log.Debugln("Importing", jid, "for", user)
  741. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  742. if len(portal.MXID) > 0 {
  743. portal.Sync(user, contact)
  744. ce.Reply("Portal room synced.")
  745. } else {
  746. portal.Sync(user, contact)
  747. ce.Reply("Portal room created.")
  748. }
  749. _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  750. }
  751. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  752. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  753. if len(ce.Args) == 0 {
  754. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  755. return
  756. }
  757. force := ce.Args[0] == "--force"
  758. if force {
  759. ce.Args = ce.Args[1:]
  760. }
  761. user := ce.User
  762. number := strings.Join(ce.Args, "")
  763. if number[0] == '+' {
  764. number = number[1:]
  765. }
  766. for _, char := range number {
  767. if char < '0' || char > '9' {
  768. ce.Reply("Invalid phone number.")
  769. return
  770. }
  771. }
  772. jid := number + whatsapp.NewUserSuffix
  773. handler.log.Debugln("Importing", jid, "for", user)
  774. contact, ok := user.Conn.Store.Contacts[jid]
  775. if !ok {
  776. if !force {
  777. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  778. "To create a portal anyway, use `pm --force <number>`.")
  779. return
  780. }
  781. contact = whatsapp.Contact{JID: jid}
  782. }
  783. puppet := user.bridge.GetPuppetByJID(contact.JID)
  784. puppet.Sync(user, contact)
  785. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.JID, user.JID))
  786. if len(portal.MXID) > 0 {
  787. err := portal.MainIntent().EnsureInvited(portal.MXID, user.MXID)
  788. if err != nil {
  789. portal.log.Warnfln("Failed to invite %s to portal: %v. Creating new portal", user.MXID, err)
  790. } else {
  791. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  792. return
  793. }
  794. }
  795. err := portal.CreateMatrixRoom(user)
  796. if err != nil {
  797. ce.Reply("Failed to create portal room: %v", err)
  798. return
  799. }
  800. ce.Reply("Created portal room and invited you to it.")
  801. }
  802. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  803. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  804. if len(ce.Args) == 0 {
  805. ce.Reply("**Usage:** `login-matrix <access token>`")
  806. return
  807. }
  808. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  809. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  810. if err != nil {
  811. ce.Reply("Failed to switch puppet: %v", err)
  812. return
  813. }
  814. ce.Reply("Successfully switched puppet")
  815. }
  816. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  817. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  818. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  819. if len(puppet.CustomMXID) == 0 {
  820. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  821. return
  822. }
  823. err := puppet.SwitchCustomMXID("", "")
  824. if err != nil {
  825. ce.Reply("Failed to remove custom puppet: %v", err)
  826. return
  827. }
  828. ce.Reply("Successfully removed custom puppet")
  829. }