commands.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. // mautrix-whatsapp - A Matrix-WhatsApp puppeting bridge.
  2. // Copyright (C) 2021 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. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/skip2/go-qrcode"
  25. "go.mau.fi/whatsmeow/types"
  26. "go.mau.fi/whatsmeow/types/events"
  27. "maunium.net/go/maulogger/v2"
  28. "maunium.net/go/mautrix"
  29. "maunium.net/go/mautrix/appservice"
  30. "maunium.net/go/mautrix/event"
  31. "maunium.net/go/mautrix/format"
  32. "maunium.net/go/mautrix/id"
  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-session":
  111. handler.CommandDeleteSession(ce)
  112. case "delete-portal":
  113. handler.CommandDeletePortal(ce)
  114. case "delete-all-portals":
  115. handler.CommandDeleteAllPortals(ce)
  116. case "discard-megolm-session", "discard-session":
  117. handler.CommandDiscardMegolmSession(ce)
  118. case "dev-test":
  119. handler.CommandDevTest(ce)
  120. case "set-pl":
  121. handler.CommandSetPowerLevel(ce)
  122. case "logout":
  123. handler.CommandLogout(ce)
  124. case "toggle":
  125. handler.CommandToggle(ce)
  126. case "login-matrix", "sync", "list", "open", "pm", "invite-link", "join", "create":
  127. if !ce.User.HasSession() {
  128. ce.Reply("You are not logged in. Use the `login` command to log into WhatsApp.")
  129. return
  130. } else if !ce.User.IsLoggedIn() {
  131. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect.")
  132. return
  133. }
  134. switch ce.Command {
  135. case "login-matrix":
  136. handler.CommandLoginMatrix(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, use the `help` command for help.")
  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. linkifiedVersion := fmt.Sprintf("v%s", Version)
  187. if Tag == Version {
  188. linkifiedVersion = fmt.Sprintf("[v%s](%s/releases/v%s)", Version, URL, Tag)
  189. } else if len(Commit) > 8 {
  190. linkifiedVersion = strings.Replace(linkifiedVersion, Commit[:8], fmt.Sprintf("[%s](%s/commit/%s)", Commit[:8], URL, Commit), 1)
  191. }
  192. ce.Reply(fmt.Sprintf("[%s](%s) %s (%s)", Name, URL, linkifiedVersion, BuildTime))
  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. // TODO reimplement
  204. //link, err := ce.User.Conn.GroupInviteLink(ce.Portal.Key.JID)
  205. //if err != nil {
  206. // ce.Reply("Failed to get invite link: %v", err)
  207. // return
  208. //}
  209. //ce.Reply("%s%s", inviteLinkPrefix, link)
  210. }
  211. const cmdJoinHelp = `join <invite link> - Join a group chat with an invite link.`
  212. const inviteLinkPrefix = "https://chat.whatsapp.com/"
  213. func (handler *CommandHandler) CommandJoin(ce *CommandEvent) {
  214. if len(ce.Args) == 0 {
  215. ce.Reply("**Usage:** `join <invite link>`")
  216. return
  217. } else if len(ce.Args[0]) <= len(inviteLinkPrefix) || ce.Args[0][:len(inviteLinkPrefix)] != inviteLinkPrefix {
  218. ce.Reply("That doesn't look like a WhatsApp invite link")
  219. return
  220. }
  221. // TODO reimplement
  222. //jid, err := ce.User.Conn.GroupAcceptInviteCode(ce.Args[0][len(inviteLinkPrefix):])
  223. //if err != nil {
  224. // ce.Reply("Failed to join group: %v", err)
  225. // return
  226. //}
  227. //
  228. //handler.log.Debugln("%s successfully joined group %s", ce.User.MXID, jid)
  229. //portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  230. //if len(portal.MXID) > 0 {
  231. // portal.Sync(ce.User, whatsapp.Contact{JID: portal.Key.JID})
  232. // ce.Reply("Successfully joined group \"%s\" and synced portal room: [%s](https://matrix.to/#/%s)", portal.Name, portal.Name, portal.MXID)
  233. //} else {
  234. // err = portal.CreateMatrixRoom(ce.User)
  235. // if err != nil {
  236. // ce.Reply("Failed to create portal room: %v", err)
  237. // return
  238. // }
  239. //
  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 := []types.JID{ce.User.JID.ToNonAD()}
  270. for userID := range members.Joined {
  271. jid, ok := handler.bridge.ParsePuppetMXID(userID)
  272. if ok && jid.User != ce.User.JID.User {
  273. participants = append(participants, jid)
  274. }
  275. }
  276. // TODO reimplement
  277. //resp, err := ce.User.Conn.CreateGroup(roomNameEvent.Name, participants)
  278. //if err != nil {
  279. // ce.Reply("Failed to create group: %v", err)
  280. // return
  281. //}
  282. //portal := handler.bridge.GetPortalByJID(database.GroupPortalKey(resp.GroupID))
  283. //portal.roomCreateLock.Lock()
  284. //defer portal.roomCreateLock.Unlock()
  285. //if len(portal.MXID) != 0 {
  286. // portal.log.Warnln("Detected race condition in room creation")
  287. // // TODO race condition, clean up the old room
  288. //}
  289. //portal.MXID = ce.RoomID
  290. //portal.Name = roomNameEvent.Name
  291. //portal.Encrypted = encryptionEvent.Algorithm == id.AlgorithmMegolmV1
  292. //if !portal.Encrypted && handler.bridge.Config.Bridge.Encryption.Default {
  293. // _, err = portal.MainIntent().SendStateEvent(portal.MXID, event.StateEncryption, "", &event.EncryptionEventContent{Algorithm: id.AlgorithmMegolmV1})
  294. // if err != nil {
  295. // portal.log.Warnln("Failed to enable e2be:", err)
  296. // }
  297. // portal.Encrypted = true
  298. //}
  299. //
  300. //portal.Update()
  301. //portal.UpdateBridgeInfo()
  302. //
  303. //ce.Reply("Successfully created WhatsApp group %s", portal.Key.JID)
  304. //inCommunity := ce.User.addPortalToCommunity(portal)
  305. //ce.User.CreateUserPortal(database.PortalKeyWithMeta{PortalKey: portal.Key, InCommunity: inCommunity})
  306. }
  307. const cmdSetPowerLevelHelp = `set-pl [user ID] <power level> - Change the power level in a portal room. Only for bridge admins.`
  308. func (handler *CommandHandler) CommandSetPowerLevel(ce *CommandEvent) {
  309. if ce.Portal == nil {
  310. ce.Reply("Not a portal room")
  311. return
  312. }
  313. var level int
  314. var userID id.UserID
  315. var err error
  316. if len(ce.Args) == 1 {
  317. level, err = strconv.Atoi(ce.Args[0])
  318. if err != nil {
  319. ce.Reply("Invalid power level \"%s\"", ce.Args[0])
  320. return
  321. }
  322. userID = ce.User.MXID
  323. } else if len(ce.Args) == 2 {
  324. userID = id.UserID(ce.Args[0])
  325. _, _, err := userID.Parse()
  326. if err != nil {
  327. ce.Reply("Invalid user ID \"%s\"", ce.Args[0])
  328. return
  329. }
  330. level, err = strconv.Atoi(ce.Args[1])
  331. if err != nil {
  332. ce.Reply("Invalid power level \"%s\"", ce.Args[1])
  333. return
  334. }
  335. } else {
  336. ce.Reply("**Usage:** `set-pl [user] <level>`")
  337. return
  338. }
  339. intent := ce.Portal.MainIntent()
  340. _, err = intent.SetPowerLevel(ce.RoomID, userID, level)
  341. if err != nil {
  342. ce.Reply("Failed to set power levels: %v", err)
  343. }
  344. }
  345. const cmdLoginHelp = `login - Authenticate this Bridge as WhatsApp Web Client`
  346. // CommandLogin handles login command
  347. func (handler *CommandHandler) CommandLogin(ce *CommandEvent) {
  348. if ce.User.Session != nil {
  349. ce.Reply("You're already logged in")
  350. return
  351. }
  352. qrChan := make(chan *events.QR, 1)
  353. loginChan := make(chan *events.PairSuccess, 1)
  354. ctx, cancel := context.WithCancel(context.Background())
  355. defer cancel()
  356. go ce.User.loginQrChannel(ctx, ce, qrChan, cancel)
  357. ce.User.qrListener = qrChan
  358. ce.User.loginListener = loginChan
  359. if !ce.User.Connect(true) {
  360. ce.User.log.Debugln("Connect() returned false, assuming error was logged elsewhere and canceling login.")
  361. return
  362. }
  363. select {
  364. case success := <-loginChan:
  365. ce.Reply("Successfully logged in as +%s (device #%d)", success.ID.User, success.ID.Device)
  366. cancel()
  367. case <-ctx.Done():
  368. ce.Reply("Login timed out")
  369. }
  370. }
  371. func (user *User) loginQrChannel(ctx context.Context, ce *CommandEvent, qrChan <-chan *events.QR, cancel func()) {
  372. var qrEvt *events.QR
  373. select {
  374. case qrEvt = <-qrChan:
  375. case <-ctx.Done():
  376. return
  377. }
  378. bot := user.bridge.AS.BotClient()
  379. code := qrEvt.Codes[0]
  380. qrEvt.Codes = qrEvt.Codes[1:]
  381. url, ok := user.uploadQR(ce, code)
  382. if !ok {
  383. return
  384. }
  385. sendResp, err := bot.SendImage(ce.RoomID, code, url)
  386. if err != nil {
  387. user.log.Errorln("Failed to send QR code to user:", err)
  388. return
  389. }
  390. qrEventID := sendResp.EventID
  391. for {
  392. select {
  393. case <-time.After(qrEvt.Timeout):
  394. if len(qrEvt.Codes) == 0 {
  395. _, _ = bot.RedactEvent(ce.RoomID, qrEventID)
  396. cancel()
  397. return
  398. }
  399. code, qrEvt.Codes = qrEvt.Codes[0], qrEvt.Codes[1:]
  400. url, ok = user.uploadQR(ce, code)
  401. if !ok {
  402. continue
  403. }
  404. _, err = bot.SendMessageEvent(ce.RoomID, event.EventMessage, &event.MessageEventContent{
  405. MsgType: event.MsgImage,
  406. Body: code,
  407. URL: url.CUString(),
  408. NewContent: &event.MessageEventContent{
  409. MsgType: event.MsgImage,
  410. Body: code,
  411. URL: url.CUString(),
  412. },
  413. RelatesTo: &event.RelatesTo{
  414. Type: event.RelReplace,
  415. EventID: qrEventID,
  416. },
  417. })
  418. if err != nil {
  419. user.log.Errorln("Failed to send edited QR code to user:", err)
  420. }
  421. case <-ctx.Done():
  422. _, _ = bot.RedactEvent(ce.RoomID, qrEventID)
  423. return
  424. }
  425. }
  426. }
  427. func (user *User) uploadQR(ce *CommandEvent, code string) (id.ContentURI, bool) {
  428. qrCode, err := qrcode.Encode(code, qrcode.Low, 256)
  429. if err != nil {
  430. user.log.Errorln("Failed to encode QR code:", err)
  431. ce.Reply("Failed to encode QR code: %v", err)
  432. return id.ContentURI{}, false
  433. }
  434. bot := user.bridge.AS.BotClient()
  435. resp, err := bot.UploadBytes(qrCode, "image/png")
  436. if err != nil {
  437. user.log.Errorln("Failed to upload QR code:", err)
  438. ce.Reply("Failed to upload QR code: %v", err)
  439. return id.ContentURI{}, false
  440. }
  441. return resp.ContentURI, true
  442. }
  443. const cmdLogoutHelp = `logout - Logout from WhatsApp`
  444. // CommandLogout handles !logout command
  445. func (handler *CommandHandler) CommandLogout(ce *CommandEvent) {
  446. if ce.User.Session == nil {
  447. ce.Reply("You're not logged in.")
  448. return
  449. } else if !ce.User.IsLoggedIn() {
  450. ce.Reply("You are not connected to WhatsApp. Use the `reconnect` command to reconnect, or `delete-session` to forget all login information.")
  451. return
  452. }
  453. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  454. if puppet.CustomMXID != "" {
  455. err := puppet.SwitchCustomMXID("", "")
  456. if err != nil {
  457. ce.User.log.Warnln("Failed to logout-matrix while logging out of WhatsApp:", err)
  458. }
  459. }
  460. // TODO reimplement
  461. //err := ce.User.Client.Logout()
  462. //if err != nil {
  463. // ce.User.log.Warnln("Error while logging out:", err)
  464. // ce.Reply("Unknown error while logging out: %v", err)
  465. // return
  466. //}
  467. ce.User.removeFromJIDMap(StateLoggedOut)
  468. ce.User.DeleteConnection()
  469. ce.User.DeleteSession()
  470. ce.Reply("Logged out successfully.")
  471. }
  472. const cmdToggleHelp = `toggle <presence|receipts|all> - Toggle bridging of presence or read receipts`
  473. func (handler *CommandHandler) CommandToggle(ce *CommandEvent) {
  474. if len(ce.Args) == 0 || (ce.Args[0] != "presence" && ce.Args[0] != "receipts" && ce.Args[0] != "all") {
  475. ce.Reply("**Usage:** `toggle <presence|receipts|all>`")
  476. return
  477. }
  478. if ce.User.Session == nil {
  479. ce.Reply("You're not logged in.")
  480. return
  481. }
  482. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  483. if customPuppet == nil {
  484. ce.Reply("You're not logged in with your Matrix account.")
  485. return
  486. }
  487. if ce.Args[0] == "presence" || ce.Args[0] == "all" {
  488. //customPuppet.EnablePresence = !customPuppet.EnablePresence
  489. //var newPresence whatsapp.Presence
  490. //if customPuppet.EnablePresence {
  491. // newPresence = whatsapp.PresenceAvailable
  492. // ce.Reply("Enabled presence bridging")
  493. //} else {
  494. // newPresence = whatsapp.PresenceUnavailable
  495. // ce.Reply("Disabled presence bridging")
  496. //}
  497. //if ce.User.IsConnected() {
  498. // _, err := ce.User.Conn.Presence("", newPresence)
  499. // if err != nil {
  500. // ce.User.log.Warnln("Failed to set presence:", err)
  501. // }
  502. //}
  503. }
  504. if ce.Args[0] == "receipts" || ce.Args[0] == "all" {
  505. customPuppet.EnableReceipts = !customPuppet.EnableReceipts
  506. if customPuppet.EnableReceipts {
  507. ce.Reply("Enabled read receipt bridging")
  508. } else {
  509. ce.Reply("Disabled read receipt bridging")
  510. }
  511. }
  512. customPuppet.Update()
  513. }
  514. const cmdDeleteSessionHelp = `delete-session - Delete session information and disconnect from WhatsApp without sending a logout request`
  515. func (handler *CommandHandler) CommandDeleteSession(ce *CommandEvent) {
  516. if ce.User.Session == nil && ce.User.Client == nil {
  517. ce.Reply("Nothing to purge: no session information stored and no active connection.")
  518. return
  519. }
  520. ce.User.removeFromJIDMap(StateLoggedOut)
  521. ce.User.DeleteConnection()
  522. ce.User.DeleteSession()
  523. ce.Reply("Session information purged")
  524. }
  525. const cmdReconnectHelp = `reconnect - Reconnect to WhatsApp`
  526. func (handler *CommandHandler) CommandReconnect(ce *CommandEvent) {
  527. // TODO reimplement
  528. //if ce.User.Client == nil {
  529. // if ce.User.Session == nil {
  530. // ce.Reply("No existing connection and no session. Did you mean `login`?")
  531. // } else {
  532. // ce.Reply("No existing connection, creating one...")
  533. // ce.User.Connect(false)
  534. // }
  535. // return
  536. //}
  537. //
  538. //wasConnected := true
  539. //ce.User.Client.Disconnect()
  540. //ctx := context.Background()
  541. //connected := ce.User.Connect(false)
  542. //
  543. //err = ce.User.Conn.Restore(true, ctx)
  544. //if err == whatsapp.ErrInvalidSession {
  545. // if ce.User.Session != nil {
  546. // ce.User.log.Debugln("Got invalid session error when reconnecting, but user has session. Retrying using RestoreWithSession()...")
  547. // ce.User.Conn.SetSession(*ce.User.Session)
  548. // err = ce.User.Conn.Restore(true, ctx)
  549. // } else {
  550. // ce.Reply("You are not logged in.")
  551. // return
  552. // }
  553. //} else if err == whatsapp.ErrLoginInProgress {
  554. // ce.Reply("A login or reconnection is already in progress.")
  555. // return
  556. //} else if err == whatsapp.ErrAlreadyLoggedIn {
  557. // ce.Reply("You were already connected.")
  558. // return
  559. //}
  560. //if err != nil {
  561. // ce.User.log.Warnln("Error while reconnecting:", err)
  562. // ce.Reply("Unknown error while reconnecting: %v", err)
  563. // ce.User.log.Debugln("Disconnecting due to failed session restore in reconnect command...")
  564. // err = ce.User.Conn.Disconnect()
  565. // if err != nil {
  566. // ce.User.log.Errorln("Failed to disconnect after failed session restore in reconnect command:", err)
  567. // }
  568. // return
  569. //}
  570. //ce.User.ConnectionErrors = 0
  571. //
  572. //var msg string
  573. //if wasConnected {
  574. // msg = "Reconnected successfully."
  575. //} else {
  576. // msg = "Connected successfully."
  577. //}
  578. //ce.Reply(msg)
  579. //ce.User.PostLogin()
  580. }
  581. const cmdDisconnectHelp = `disconnect - Disconnect from WhatsApp (without logging out)`
  582. func (handler *CommandHandler) CommandDisconnect(ce *CommandEvent) {
  583. if ce.User.Client == nil {
  584. ce.Reply("You don't have a WhatsApp connection.")
  585. return
  586. }
  587. ce.User.DeleteConnection()
  588. ce.Reply("Successfully disconnected. Use the `reconnect` command to reconnect.")
  589. }
  590. const cmdPingHelp = `ping - Check your connection to WhatsApp.`
  591. func (handler *CommandHandler) CommandPing(ce *CommandEvent) {
  592. if ce.User.Session == nil {
  593. ce.Reply("You're not logged into WhatsApp.")
  594. } else if ce.User.Client == nil || !ce.User.Client.IsConnected() {
  595. ce.Reply("You don't have a WhatsApp connection.")
  596. } else {
  597. ce.Reply("Connection to WhatsApp OK (probably)")
  598. }
  599. }
  600. const cmdHelpHelp = `help - Prints this help`
  601. // CommandHelp handles help command
  602. func (handler *CommandHandler) CommandHelp(ce *CommandEvent) {
  603. cmdPrefix := ""
  604. if ce.User.ManagementRoom != ce.RoomID || ce.User.IsRelaybot {
  605. cmdPrefix = handler.bridge.Config.Bridge.CommandPrefix + " "
  606. }
  607. ce.Reply("* " + strings.Join([]string{
  608. cmdPrefix + cmdHelpHelp,
  609. cmdPrefix + cmdVersionHelp,
  610. cmdPrefix + cmdLoginHelp,
  611. cmdPrefix + cmdLogoutHelp,
  612. cmdPrefix + cmdDeleteSessionHelp,
  613. cmdPrefix + cmdReconnectHelp,
  614. cmdPrefix + cmdDisconnectHelp,
  615. cmdPrefix + cmdPingHelp,
  616. cmdPrefix + cmdLoginMatrixHelp,
  617. cmdPrefix + cmdLogoutMatrixHelp,
  618. cmdPrefix + cmdToggleHelp,
  619. cmdPrefix + cmdListHelp,
  620. cmdPrefix + cmdOpenHelp,
  621. cmdPrefix + cmdPMHelp,
  622. cmdPrefix + cmdInviteLinkHelp,
  623. cmdPrefix + cmdJoinHelp,
  624. cmdPrefix + cmdCreateHelp,
  625. cmdPrefix + cmdSetPowerLevelHelp,
  626. cmdPrefix + cmdDeletePortalHelp,
  627. cmdPrefix + cmdDeleteAllPortalsHelp,
  628. }, "\n* "))
  629. }
  630. const cmdDeletePortalHelp = `delete-portal - Delete the current portal. If the portal is used by other people, this is limited to bridge admins.`
  631. func (handler *CommandHandler) CommandDeletePortal(ce *CommandEvent) {
  632. if ce.Portal == nil {
  633. ce.Reply("You must be in a portal room to use that command")
  634. return
  635. }
  636. if !ce.User.Admin {
  637. // TODO reimplement
  638. //users := ce.Portal.GetUserIDs()
  639. //if len(users) > 1 || (len(users) == 1 && users[0] != ce.User.MXID) {
  640. // ce.Reply("Only bridge admins can delete portals with other Matrix users")
  641. // return
  642. //}
  643. return
  644. }
  645. ce.Portal.log.Infoln(ce.User.MXID, "requested deletion of portal.")
  646. ce.Portal.Delete()
  647. ce.Portal.Cleanup(false)
  648. }
  649. const cmdDeleteAllPortalsHelp = `delete-all-portals - Delete all your portals that aren't used by any other user.`
  650. func (handler *CommandHandler) CommandDeleteAllPortals(ce *CommandEvent) {
  651. // TODO reimplement
  652. //portals := ce.User.GetPortals()
  653. //portalsToDelete := make([]*Portal, 0, len(portals))
  654. //for _, portal := range portals {
  655. // users := portal.GetUserIDs()
  656. // if len(users) == 1 && users[0] == ce.User.MXID {
  657. // portalsToDelete = append(portalsToDelete, portal)
  658. // }
  659. //}
  660. if !ce.User.Admin {
  661. return
  662. }
  663. portalsToDelete := handler.bridge.GetAllPortals()
  664. leave := func(portal *Portal) {
  665. if len(portal.MXID) > 0 {
  666. _, _ = portal.MainIntent().KickUser(portal.MXID, &mautrix.ReqKickUser{
  667. Reason: "Deleting portal",
  668. UserID: ce.User.MXID,
  669. })
  670. }
  671. }
  672. customPuppet := handler.bridge.GetPuppetByCustomMXID(ce.User.MXID)
  673. if customPuppet != nil && customPuppet.CustomIntent() != nil {
  674. intent := customPuppet.CustomIntent()
  675. leave = func(portal *Portal) {
  676. if len(portal.MXID) > 0 {
  677. _, _ = intent.LeaveRoom(portal.MXID)
  678. _, _ = intent.ForgetRoom(portal.MXID)
  679. }
  680. }
  681. }
  682. ce.Reply("Found %d portals with no other users, deleting...", len(portalsToDelete))
  683. for _, portal := range portalsToDelete {
  684. portal.Delete()
  685. leave(portal)
  686. }
  687. ce.Reply("Finished deleting portal info. Now cleaning up rooms in background. " +
  688. "You may already continue using the bridge. Use `sync` to recreate portals.")
  689. go func() {
  690. for _, portal := range portalsToDelete {
  691. portal.Cleanup(false)
  692. }
  693. ce.Reply("Finished background cleanup of deleted portal rooms.")
  694. }()
  695. }
  696. const cmdListHelp = `list <contacts|groups> [page] [items per page] - Get a list of all contacts and groups.`
  697. //func formatContacts(contacts bool, input map[string]whatsapp.Contact) (result []string) {
  698. // for jid, contact := range input {
  699. // if strings.HasSuffix(jid, whatsapp.NewUserSuffix) != contacts {
  700. // continue
  701. // }
  702. //
  703. // if contacts {
  704. // result = append(result, fmt.Sprintf("* %s / %s - `%s`", contact.Name, contact.Notify, contact.JID[:len(contact.JID)-len(whatsapp.NewUserSuffix)]))
  705. // } else {
  706. // result = append(result, fmt.Sprintf("* %s - `%s`", contact.Name, contact.JID))
  707. // }
  708. // }
  709. // sort.Sort(sort.StringSlice(result))
  710. // return
  711. //}
  712. func (handler *CommandHandler) CommandList(ce *CommandEvent) {
  713. if len(ce.Args) == 0 {
  714. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  715. return
  716. }
  717. mode := strings.ToLower(ce.Args[0])
  718. if mode[0] != 'g' && mode[0] != 'c' {
  719. ce.Reply("**Usage:** `list <contacts|groups> [page] [items per page]`")
  720. return
  721. }
  722. var err error
  723. page := 1
  724. max := 100
  725. if len(ce.Args) > 1 {
  726. page, err = strconv.Atoi(ce.Args[1])
  727. if err != nil || page <= 0 {
  728. ce.Reply("\"%s\" isn't a valid page number", ce.Args[1])
  729. return
  730. }
  731. }
  732. if len(ce.Args) > 2 {
  733. max, err = strconv.Atoi(ce.Args[2])
  734. if err != nil || max <= 0 {
  735. ce.Reply("\"%s\" isn't a valid number of items per page", ce.Args[2])
  736. return
  737. } else if max > 400 {
  738. ce.Reply("Warning: a high number of items per page may fail to send a reply")
  739. }
  740. }
  741. // TODO reimplement
  742. //contacts := mode[0] == 'c'
  743. //typeName := "Groups"
  744. //if contacts {
  745. // typeName = "Contacts"
  746. //}
  747. //ce.User.Conn.Store.ContactsLock.RLock()
  748. //result := formatContacts(contacts, ce.User.Conn.Store.Contacts)
  749. //ce.User.Conn.Store.ContactsLock.RUnlock()
  750. //if len(result) == 0 {
  751. // ce.Reply("No %s found", strings.ToLower(typeName))
  752. // return
  753. //}
  754. //pages := int(math.Ceil(float64(len(result)) / float64(max)))
  755. //if (page-1)*max >= len(result) {
  756. // if pages == 1 {
  757. // ce.Reply("There is only 1 page of %s", strings.ToLower(typeName))
  758. // } else {
  759. // ce.Reply("There are only %d pages of %s", pages, strings.ToLower(typeName))
  760. // }
  761. // return
  762. //}
  763. //lastIndex := page * max
  764. //if lastIndex > len(result) {
  765. // lastIndex = len(result)
  766. //}
  767. //result = result[(page-1)*max : lastIndex]
  768. //ce.Reply("### %s (page %d of %d)\n\n%s", typeName, page, pages, strings.Join(result, "\n"))
  769. }
  770. const cmdOpenHelp = `open <_group JID_> - Open a group chat portal.`
  771. func (handler *CommandHandler) CommandOpen(ce *CommandEvent) {
  772. if len(ce.Args) == 0 {
  773. ce.Reply("**Usage:** `open <group JID>`")
  774. return
  775. }
  776. // TODO reimplement
  777. //user := ce.User
  778. //jid := ce.Args[0]
  779. //if strings.HasSuffix(jid, whatsapp.NewUserSuffix) {
  780. // ce.Reply("That looks like a user JID. Did you mean `pm %s`?", jid[:len(jid)-len(whatsapp.NewUserSuffix)])
  781. // return
  782. //}
  783. //
  784. //user.Conn.Store.ContactsLock.RLock()
  785. //contact, ok := user.Conn.Store.Contacts[jid]
  786. //user.Conn.Store.ContactsLock.RUnlock()
  787. //if !ok {
  788. // ce.Reply("Group JID not found in contacts. Try syncing contacts with `sync` first.")
  789. // return
  790. //}
  791. //handler.log.Debugln("Importing", jid, "for", user)
  792. //portal := user.bridge.GetPortalByJID(database.GroupPortalKey(jid))
  793. //if len(portal.MXID) > 0 {
  794. // portal.Sync(user, contact)
  795. // ce.Reply("Portal room synced.")
  796. //} else {
  797. // portal.Sync(user, contact)
  798. // ce.Reply("Portal room created.")
  799. //}
  800. //_, _ = portal.MainIntent().InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  801. }
  802. const cmdPMHelp = `pm <_international phone number_> - Open a private chat with the given phone number.`
  803. func (handler *CommandHandler) CommandPM(ce *CommandEvent) {
  804. if len(ce.Args) == 0 {
  805. ce.Reply("**Usage:** `pm <international phone number>`")
  806. return
  807. }
  808. user := ce.User
  809. number := strings.Join(ce.Args, "")
  810. resp, err := ce.User.Client.IsOnWhatsApp([]string{number})
  811. if err != nil {
  812. ce.Reply("Failed to check if user is on WhatsApp: %v", err)
  813. return
  814. } else if len(resp) == 0 {
  815. ce.Reply("Didn't get a response to checking if the user is on WhatsApp")
  816. return
  817. }
  818. targetUser := resp[0]
  819. if !targetUser.IsIn {
  820. ce.Reply("The server said +%s is not on WhatsApp", targetUser.JID.User)
  821. return
  822. }
  823. handler.log.Debugln("Importing", targetUser.JID, "for", user)
  824. puppet := user.bridge.GetPuppetByJID(targetUser.JID)
  825. puppet.SyncContact(user, true)
  826. portal := user.GetPortalByJID(puppet.JID)
  827. if len(portal.MXID) > 0 {
  828. if !user.IsRelaybot {
  829. _, err = portal.MainIntent().Client.InviteUser(portal.MXID, &mautrix.ReqInviteUser{UserID: user.MXID})
  830. if httpErr, ok := err.(mautrix.HTTPError); ok && httpErr.RespError != nil && strings.Contains(httpErr.RespError.Err, "is already in the room") {
  831. err = nil
  832. }
  833. }
  834. if err != nil {
  835. portal.log.Warnfln("Failed to invite %s to portal: %v. Creating new portal", user.MXID, err)
  836. portal.MXID = ""
  837. } else {
  838. ce.Reply("You already have a private chat portal with that user at [%s](https://matrix.to/#/%s)", puppet.Displayname, portal.MXID)
  839. return
  840. }
  841. }
  842. err = portal.CreateMatrixRoom(user)
  843. if err != nil {
  844. ce.Reply("Failed to create portal room: %v", err)
  845. return
  846. }
  847. ce.Reply("Created portal room and invited you to it.")
  848. }
  849. const cmdLoginMatrixHelp = `login-matrix <_access token_> - Replace your WhatsApp account's Matrix puppet with your real Matrix account.`
  850. func (handler *CommandHandler) CommandLoginMatrix(ce *CommandEvent) {
  851. if len(ce.Args) == 0 {
  852. ce.Reply("**Usage:** `login-matrix <access token>`")
  853. return
  854. }
  855. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  856. err := puppet.SwitchCustomMXID(ce.Args[0], ce.User.MXID)
  857. if err != nil {
  858. ce.Reply("Failed to switch puppet: %v", err)
  859. return
  860. }
  861. ce.Reply("Successfully switched puppet")
  862. }
  863. const cmdLogoutMatrixHelp = `logout-matrix - Switch your WhatsApp account's Matrix puppet back to the default one.`
  864. func (handler *CommandHandler) CommandLogoutMatrix(ce *CommandEvent) {
  865. puppet := handler.bridge.GetPuppetByJID(ce.User.JID)
  866. if len(puppet.CustomMXID) == 0 {
  867. ce.Reply("You had not changed your WhatsApp account's Matrix puppet.")
  868. return
  869. }
  870. err := puppet.SwitchCustomMXID("", "")
  871. if err != nil {
  872. ce.Reply("Failed to remove custom puppet: %v", err)
  873. return
  874. }
  875. ce.Reply("Successfully removed custom puppet")
  876. }