commands.go 27 KB

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