commands.go 28 KB

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