commands.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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. linkifiedVersion := fmt.Sprintf("v%s", Version)
  191. if Tag == Version {
  192. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  193. } else if len(Commit) > 8 {
  194. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  195. }
  196. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  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(StateLoggedOut)
  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 or read receipts`
  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. }
  413. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  414. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  415. if customPuppet.EnableReceipts {
  416. ce.Reply("Enabled read receipt bridging")
  417. } else {
  418. ce.Reply("Disabled read receipt bridging")
  419. }
  420. }
  421. customPuppet.Update()
  422. }
  423. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  424. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  425. if ce.User.Session == nil && ce.User.Conn == nil {
  426. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  427. return
  428. }
  429. //ce.User.JID = ""
  430. ce.User.removeFromJIDMap(StateLoggedOut)
  431. ce.User.SetSession(nil)
  432. ce.User.DeleteConnection()
  433. ce.Reply("Session information purged")
  434. }
  435. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  436. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  437. if ce.User.Conn == nil {
  438. if ce.User.Session == nil {
  439. ce.Reply("No existing connection and no session. Did you mean `login`?")
  440. } else {
  441. ce.Reply("No existing connection, creating one...")
  442. ce.User.Connect(false)
  443. }
  444. return
  445. }
  446. wasConnected := true
  447. err := ce.User.Conn.Disconnect()
  448. if err == whatsapp.ErrNotConnected {
  449. wasConnected = false
  450. } else if err != nil {
  451. ce.User.log.Warnln("Error while disconnecting:", err)
  452. }
  453. ctx := context.Background()
  454. err = ce.User.Conn.Restore(true, ctx)
  455. if err == whatsapp.ErrInvalidSession {
  456. if ce.User.Session != nil {
  457. ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  458. ce.User.Conn.SetSession(*ce.User.Session)
  459. err = ce.User.Conn.Restore(true, ctx)
  460. } else {
  461. ce.Reply("You are not logged in.")
  462. return
  463. }
  464. } else if err == whatsapp.ErrLoginInProgress {
  465. ce.Reply("A login or reconnection is already in progress.")
  466. return
  467. } else if err == whatsapp.ErrAlreadyLoggedIn {
  468. ce.Reply("You were already connected.")
  469. return
  470. }
  471. if err != nil {
  472. ce.User.log.Warnln("Error while reconnecting:", err)
  473. ce.Reply("Unknown error while reconnecting: %v", err)
  474. ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  475. err = ce.User.Conn.Disconnect()
  476. if err != nil {
  477. ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  478. }
  479. return
  480. }
  481. ce.User.ConnectionErrors = 0
  482. var msg string
  483. if wasConnected {
  484. msg = "Reconnected successfully."
  485. } else {
  486. msg = "Connected successfully."
  487. }
  488. ce.Reply(msg)
  489. ce.User.PostLogin()
  490. }
  491. const cmdDeleteConnectionHelp = `delete-connection - Disconnect ignoring errors and delete internal connection state.`
  492. func (handler *CommandHandler) CommandDeleteConnection(ce *CommandEvent) {
  493. if ce.User.Conn == nil {
  494. ce.Reply("You don't have a WhatsApp connection.")
  495. return
  496. }
  497. ce.User.DeleteConnection()
  498. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  499. }
  500. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  501. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  502. if ce.User.Conn == nil {
  503. ce.Reply("You don't have a WhatsApp connection.")
  504. return
  505. }
  506. err := ce.User.Conn.Disconnect()
  507. if err == whatsapp.ErrNotConnected {
  508. ce.Reply("You were not connected.")
  509. return
  510. } else if err != nil {
  511. ce.User.log.Warnln("Error while disconnecting:", err)
  512. ce.Reply("Unknown error while disconnecting: %v", err)
  513. return
  514. }
  515. ce.User.bridge.Metrics.TrackConnectionState(ce.User.JID, false)
  516. ce.User.sendBridgeState(BridgeState{StateEvent: StateBadCredentials, Error: WANotConnected})
  517. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  518. }
  519. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  520. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  521. if ce.User.Session == nil {
  522. if ce.User.IsLoginInProgress() {
  523. ce.Reply("You're not logged into WhatsApp, but there's a login in progress.")
  524. } else {
  525. ce.Reply("You're not logged into WhatsApp.")
  526. }
  527. } else if ce.User.Conn == nil {
  528. ce.Reply("You don't have a WhatsApp connection.")
  529. } else if err := ce.User.Conn.AdminTest(); err != nil {
  530. if ce.User.IsLoginInProgress() {
  531. ce.Reply("Connection not OK: %v, but login in progress", err)
  532. } else {
  533. ce.Reply("Connection not OK: %v", err)
  534. }
  535. } else {
  536. ce.Reply("Connection to WhatsApp OK")
  537. }
  538. }
  539. const cmdHelpHelp = `help - Prints this help`
  540. // CommandHelp handles help command
  541. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  542. cmdPrefix := ""
  543. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  544. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  545. }
  546. ce.Reply("* " + strings.Join([]string{
  547. cmdPrefix + cmdHelpHelp,
  548. cmdPrefix + cmdVersionHelp,
  549. cmdPrefix + cmdLoginHelp,
  550. cmdPrefix + cmdLogoutHelp,
  551. cmdPrefix + cmdDeleteSessionHelp,
  552. cmdPrefix + cmdReconnectHelp,
  553. cmdPrefix + cmdDisconnectHelp,
  554. cmdPrefix + cmdDeleteConnectionHelp,
  555. cmdPrefix + cmdPingHelp,
  556. cmdPrefix + cmdLoginMatrixHelp,
  557. cmdPrefix + cmdLogoutMatrixHelp,
  558. cmdPrefix + cmdToggleHelp,
  559. cmdPrefix + cmdSyncHelp,
  560. cmdPrefix + cmdListHelp,
  561. cmdPrefix + cmdOpenHelp,
  562. cmdPrefix + cmdPMHelp,
  563. cmdPrefix + cmdInviteLinkHelp,
  564. cmdPrefix + cmdJoinHelp,
  565. cmdPrefix + cmdCreateHelp,
  566. cmdPrefix + cmdSetPowerLevelHelp,
  567. cmdPrefix + cmdDeletePortalHelp,
  568. cmdPrefix + cmdDeleteAllPortalsHelp,
  569. }, "\n* "))
  570. }
  571. const cmdSyncHelp = `sync [--create-all] - Synchronize contacts from phone and optionally create portals for group chats.`
  572. // CommandSync handles sync command
  573. func (handler *CommandHandler) CommandSync(ce *CommandEvent) {
  574. user := ce.User
  575. create := len(ce.Args) > 0 && ce.Args[0] == "--create-all"
  576. ce.Reply("Updating contact and chat list...")
  577. handler.log.Debugln("Importing contacts of", user.MXID)
  578. _, err := user.Conn.Contacts()
  579. if err != nil {
  580. user.log.Errorln("Error updating contacts:", err)
  581. ce.Reply("Failed to sync contact list (see logs for details)")
  582. return
  583. }
  584. handler.log.Debugln("Importing chats of", user.MXID)
  585. _, err = user.Conn.Chats()
  586. if err != nil {
  587. user.log.Errorln("Error updating chats:", err)
  588. ce.Reply("Failed to sync chat list (see logs for details)")
  589. return
  590. }
  591. ce.Reply("Syncing contacts...")
  592. user.syncPuppets(nil)
  593. ce.Reply("Syncing chats...")
  594. user.syncPortals(nil, create)
  595. ce.Reply("Sync complete.")
  596. }
  597. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  598. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  599. if ce.Portal == nil {
  600. ce.Reply("You must be in a portal room to use that command")
  601. return
  602. }
  603. if !ce.User.Admin {
  604. users := ce.Portal.GetUserIDs()
  605. if len(users) > 1 || (len(users) == 1 && users[0] != ce.User.MXID) {
  606. ce.Reply("Only bridge admins can delete portals with other Matrix users")
  607. return
  608. }
  609. }
  610. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  611. ce.Portal.Delete()
  612. ce.Portal.Cleanup(false)
  613. }
  614. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all your portals that aren't used by any other user.'`
  615. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  616. portals := ce.User.GetPortals()
  617. portalsToDelete := make([]*Portal, 0, len(portals))
  618. for _, portal := range portals {
  619. users := portal.GetUserIDs()
  620. if len(users) == 1 && users[0] == ce.User.MXID {
  621. portalsToDelete = append(portalsToDelete, portal)
  622. }
  623. }
  624. leave := func(portal *Portal) {
  625. if len(portal.MXID) > 0 {
  626. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  627. Reason: "Deleting portal",
  628. UserID: ce.User.MXID,
  629. })
  630. }
  631. }
  632. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  633. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  634. intent := customPuppet.CustomIntent()
  635. leave = func(portal *Portal) {
  636. if len(portal.MXID) > 0 {
  637. _, _ = intent.LeaveRoom(portal.MXID)
  638. _, _ = intent.ForgetRoom(portal.MXID)
  639. }
  640. }
  641. }
  642. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  643. for _, portal := range portalsToDelete {
  644. portal.Delete()
  645. leave(portal)
  646. }
  647. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  648. "You may already continue using the bridge. Use `sync` to recreate portals.")
  649. go func() {
  650. for _, portal := range portalsToDelete {
  651. portal.Cleanup(false)
  652. }
  653. ce.Reply("Finished background cleanup of deleted portal rooms.")
  654. }()
  655. }
  656. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  657. func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  658. for jid, contact := range input {
  659. if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  660. continue
  661. }
  662. if contacts {
  663. result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  664. } else {
  665. result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  666. }
  667. }
  668. sort.Sort(sort.StringSlice(result))
  669. return
  670. }
  671. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  672. if len(ce.Args) == 0 {
  673. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  674. return
  675. }
  676. mode := strings.ToLower(ce.Args[0])
  677. if mode[0] != 'g' && mode[0] != 'c' {
  678. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  679. return
  680. }
  681. var err error
  682. page := 1
  683. max := 100
  684. if len(ce.Args) > 1 {
  685. page, err = strconv.Atoi(ce.Args[1])
  686. if err != nil || page <= 0 {
  687. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  688. return
  689. }
  690. }
  691. if len(ce.Args) > 2 {
  692. max, err = strconv.Atoi(ce.Args[2])
  693. if err != nil || max <= 0 {
  694. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  695. return
  696. } else if max > 400 {
  697. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  698. }
  699. }
  700. contacts := mode[0] == 'c'
  701. typeName := "Groups"
  702. if contacts {
  703. typeName = "Contacts"
  704. }
  705. ce.User.Conn.Store.ContactsLock.RLock()
  706. result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  707. ce.User.Conn.Store.ContactsLock.RUnlock()
  708. if len(result) == 0 {
  709. ce.Reply("No %s found", strings.ToLower(typeName))
  710. return
  711. }
  712. pages := int(math.Ceil(float64(len(result)) / float64(max)))
  713. if (page-1)*max >= len(result) {
  714. if pages == 1 {
  715. ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  716. } else {
  717. ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  718. }
  719. return
  720. }
  721. lastIndex := page * max
  722. if lastIndex > len(result) {
  723. lastIndex = len(result)
  724. }
  725. result = result[(page-1)*max : lastIndex]
  726. ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  727. }
  728. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  729. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  730. if len(ce.Args) == 0 {
  731. ce.Reply("**Usage:** `open <group JID>`")
  732. return
  733. }
  734. user := ce.User
  735. jid := ce.Args[0]
  736. if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  737. ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  738. return
  739. }
  740. user.Conn.Store.ContactsLock.RLock()
  741. contact, ok := user.Conn.Store.Contacts[jid]
  742. user.Conn.Store.ContactsLock.RUnlock()
  743. if !ok {
  744. ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  745. return
  746. }
  747. handler.log.Debugln("Importing", jid, "for", user)
  748. portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  749. if len(portal.MXID) > 0 {
  750. portal.Sync(user, contact)
  751. ce.Reply("Portal room synced.")
  752. } else {
  753. portal.Sync(user, contact)
  754. ce.Reply("Portal room created.")
  755. }
  756. _, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  757. }
  758. const cmdPMHelp = `pm [--force] <_international phone number_> - Open a private chat with the given phone number.`
  759. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  760. if len(ce.Args) == 0 {
  761. ce.Reply("**Usage:** `pm [--force] <international phone number>`")
  762. return
  763. }
  764. force := ce.Args[0] == "--force"
  765. if force {
  766. ce.Args = ce.Args[1:]
  767. }
  768. user := ce.User
  769. number := strings.Join(ce.Args, "")
  770. if number[0] == '+' {
  771. number = number[1:]
  772. }
  773. for _, char := range number {
  774. if char < '0' || char > '9' {
  775. ce.Reply("Invalid phone number.")
  776. return
  777. }
  778. }
  779. jid := number + whatsapp.NewUserSuffix
  780. handler.log.Debugln("Importing", jid, "for", user)
  781. user.Conn.Store.ContactsLock.RLock()
  782. contact, ok := user.Conn.Store.Contacts[jid]
  783. user.Conn.Store.ContactsLock.RUnlock()
  784. if !ok {
  785. if !force {
  786. ce.Reply("Phone number not found in contacts. Try syncing contacts with `sync` first. " +
  787. "To create a portal anyway, use `pm --force <number>`.")
  788. return
  789. }
  790. contact = whatsapp.Contact{JID: jid}
  791. }
  792. puppet := user.bridge.GetPuppetByJID(contact.JID)
  793. puppet.Sync(user, contact)
  794. portal := user.bridge.GetPortalByJID(database.NewPortalKey(contact.JID, user.JID))
  795. if len(portal.MXID) > 0 {
  796. var err error
  797. if !user.IsRelaybot {
  798. err = portal.MainIntent().EnsureInvited(portal.MXID, user.MXID)
  799. }
  800. if err != nil {
  801. portal.log.Warnfln("Failed to invite %s to portal: %v. Creating new portal", user.MXID, err)
  802. portal.MXID = ""
  803. } else {
  804. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  805. return
  806. }
  807. }
  808. err := portal.CreateMatrixRoom(user)
  809. if err != nil {
  810. ce.Reply("Failed to create portal room: %v", err)
  811. return
  812. }
  813. ce.Reply("Created portal room and invited you to it.")
  814. }
  815. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.'`
  816. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  817. if len(ce.Args) == 0 {
  818. ce.Reply("**Usage:** `login-matrix <access token>`")
  819. return
  820. }
  821. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  822. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  823. if err != nil {
  824. ce.Reply("Failed to switch puppet: %v", err)
  825. return
  826. }
  827. ce.Reply("Successfully switched puppet")
  828. }
  829. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  830. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  831. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  832. if len(puppet.CustomMXID) == 0 {
  833. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  834. return
  835. }
  836. err := puppet.SwitchCustomMXID("", "")
  837. if err != nil {
  838. ce.Reply("Failed to remove custom puppet: %v", err)
  839. return
  840. }
  841. ce.Reply("Successfully removed custom puppet")
  842. }