commands.go 29 KB

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