commands.go 27 KB

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