commands.go 28 KB

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