commands.go 29 KB

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