commands.go 28 KB

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