commands.go 28 KB

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